React Hooks:
Hooks are built-in React functions that allow Functional Components to use React features such as state management, lifecycle methods, context, references, and performance optimizations without writing Class Components.Hooks were introduced in React 16.8.
Why Use Hooks?
- Reusing stateful logic between components
- Managing complex component lifecycle code
- Reducing the need for Class Components
- Making components simpler and easier to understand.
Before Hooks, Functional Components could only receive props and render UI. They could not manage state or lifecycle behavior. Hooks changed that.
1.useState Hook:
The React useState Hook allows us to track state in a function component.State generally refers to data or properties that need to be tracking in an application.
Import useState
To use the useState Hook, first need to import it into component.
Example:
At the top of component, import the useState Hook.
import { useState } from "react";
useState accepts an initial state and returns two values:
*The current state.
*A function that updates the state.
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("red");
}
explanation;
The first value, color, is current state.
The second value, setColor, is the function that is used to update state.
Read State explample:
output:
Update State
output:
2.useEffect Hook:
- The useEffect Hook allows to perform side effects in components.
- Some examples of side effects are: fetching data, directly updating the DOM, and timers.
- useEffect accepts two arguments. The second argument is optional. useEffect(, )




Top comments (0)