What is useEffect hook in React and how to use it?
The useEffect
hook in React is used to handle side effects in functional components, such as:
- Fetching data from an API.
- Manipulating the DOM.
- Setting up subscriptions or timers.
This hook runs on every render but there is a way of using a dependency array using which we can control the effect of rendering.
Syntax:
useEffect(() => {
// Effect code here (e.g., API calls, subscriptions)
return () => {
// Cleanup code here (optional)
};
}, [dependencies]);
Parameters:
Effect Function: A function that contains the code for the side effect.
Cleanup function: This optional return function cleans up side effects when the component unmounts.
Dependencies Array: A list of dependencies that the effect depends on. The effect re-runs only when one of these dependencies changes.
Example:
import { useState, useEffect } from "react";
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setTime((prevTime) => prevTime + 1);
}, 1000);
// Cleanup function to clear the interval
return () => clearInterval(interval);
}, []); // Runs once, sets up interval
return <div>Time: {time}s</div>;
}