Unit 4 React Components
Unit 4 React Components
React Hooks are functions that enable functional components to use React
state and lifecycle features. They eliminate the need for class
components, making code cleaner and easier to maintain.
1. State Hooks
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() =>
setCount(count + 1)}>Increment</button>
</div>
);
}
Clicking the button updates the state using the setCount function.
2. Context Hooks
function Theme() {
const theme = useContext(Contexts);
return <h1>Theme: {theme}</h1>;
}
3. Ref Hooks
Ref Hooks like useRef provide access to DOM nodes or persist values
without causing re-renders.
function Focus() {
const input = useRef();
return (
<div>
<input ref={input} type="text" />
<button onClick={focus}>Focus</button>
</div>
);
}
4. Effect Hooks
Effect Hooks like useEffect handle side effects like fetching data,
subscriptions, and DOM manipulation.
import React, { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() =>
setSeconds((s) => s + 1), 1000);
return () => clearInterval(interval);
}, []);
5. Performance Hooks
6. Resource Hooks
useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => setData(data));
}, [url]);
return data;
}
useFetch is a custom hook for fetching data from a given URL.
It uses useEffect to fetch data when the URL changes and updates
the data state.
cd my-app
npm start
Props
Props are read-only components. It is an object which stores the value
of attributes of a tag and work similar to the HTML attributes.
It allows passing data from one component to other components.
It is similar to function arguments and can be passed to the component
the same way as arguments passed in a
Hooks:
React Hooks
Hooks are the new feature introduced in the React 16.8
version. It allows you to use state and other React features
without writing a class. Hooks are the functions which
"hook into" React state and lifecycle features from
function components. It does not work inside classes.
Hooks are backward-compatible, which means it does not
contain any breaking changes. Also, it does not replace
your knowledge of React concepts.
When to use a Hooks
If you write a function component, and then you want to add
some state to it, previously you do this by converting it to a
class. But, now you can do it by using a Hook inside the existing
function component.
Types of React Hooks
Rules of Hooks
Hooks are similar to JavaScript functions, but you need to follow
these two rules when using them. Hooks rule ensures that all
the stateful logic in a component is visible in its source code.
These rules are:
1. Only call Hooks at the top level
Do not call Hooks inside loops, conditions, or nested functions.
Hooks should always be used at the top level of the React
functions. This rule ensures that Hooks are called in the same
order each time a components renders.
2. Only call Hooks from React functions
You cannot call Hooks from regular JavaScript functions.
Instead, you can call Hooks from React function components.
Hooks can also be called from custom Hooks.
Pre-requisites for React Hooks
1. Node version 6 or above
2. NPM version 5.2 or above
3. Create-react-app tool for running the React App
6. "react": "^16.8.0-alpha.1",
7. "react-dom": "^16.8.0-alpha.1",
Example App.js
import React, { useState } from "react";
function FavoriteColor() {
<>
<button
type="button"
>Blue</button>
<button
type="button"
>Red</button>
<button
type="button"
>Pink</button>
<button
type="button"
>Green</button>
</>
);
root.render(<FavoriteColor />);
Index.js
import React from "react";
import ReactDOM from "react-dom/client";
import FavoriteColor from "./App"; // Import
FavoriteColor
const root =
ReactDOM.createRoot(document.getElementById("root")
);
root.render(<FavoriteColor />);
output
Defined with
Defined with the class keyword regular
and extends React.Component JavaScript
functions
Use useState()
Use setState() method
hook
Create custom
Utilize higher-order components and
hooks for code
render props for code reuse
reuse
Promote a more
functional
Can become complex due to managing
approach,
state, lifecycle methods, etc.
leading to
simpler code
Designed to be
Can have performance overhead due to more efficient
lifecycle methods and improve
performance