React Hooks like useState and useEffect allow functional components to manage state and side effects, which previously required class components.
🔹 1. useState
- Used to add state to functional components.
- Returns an array with two elements: the current state and a function to update it.
Example:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Explanation:
count→ current state valuesetCount→ updates state and triggers re-render
🔹 2. useEffect
- Used to perform side effects in functional components.
- Replaces lifecycle methods like
componentDidMount,componentDidUpdate, andcomponentWillUnmount.
Example:
import React, { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
// Cleanup function
return () => clearInterval(interval);
}, []); // Empty dependency → run once on mount
return <h1>Seconds: {seconds}</h1>;
}
Explanation:
- Runs after render.
- Dependencies array controls when the effect runs:
[]→ run once (mount)[stateVar]→ run whenstateVarchanges- No array → run after every render
- Cleanup function runs before unmounting or before next effect.
🔹 Key Points
| Hook | Purpose |
|---|---|
useState |
Manage state in functional components |
useEffect |
Handle side effects (API calls, timers, subscriptions) |
✅ Summary:
useState→ state managementuseEffect→ side effects and lifecycle handling