The useEffect
hook is a fundamental part of React's Hooks API, introduced in React 16.8. It allows you to perform side effects in functional components. Side effects are operations that interact with the outside world or impact the state of the component in ways other than rendering, such as data fetching, subscriptions, or manual DOM manipulations.
useEffect
Basic Usage:
useEffect
hook takes a function as its first argument. This function runs after the component renders, and it can optionally return a cleanup function to clean up side effects.useEffect(() => {
// Code to run after render
return () => {
// Cleanup code (optional)
};
}, [dependencies]); // Dependencies array
import React, { useEffect, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
// Cleanup function
return () => {
document.title = 'React App';
};
}, [count]); // Runs every time `count` changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Effect Dependencies:
useEffect
is an optional array of dependencies. The effect runs after every render by default, but specifying dependencies controls when the effect should re-run.[]
, the effect runs only once after the initial render (similar to componentDidMount
in class components).[dep1, dep2]
, the effect runs only when those dependencies change.function FetchData() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Runs only once after initial render
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Cleanup Function:
useEffect
callback and is executed before the component unmounts or before the effect runs again. This is useful for cleaning up subscriptions, timers, or other side effects.function Timer() {
useEffect(() => {
const timerId = setInterval(() => {
console.log('Timer tick');
}, 1000);
// Cleanup function
return () => {
clearInterval(timerId);
};
}, []); // Runs only once after initial render
return <div>Check the console for timer output</div>;
}
Multiple Effects:
useEffect
hooks in a single component to handle different side effects separately. This helps keep effects focused and avoids combining unrelated logic.function App() {
const [count, setCount] = useState(0);
const [data, setData] = useState(null);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<div>Data: {data ? JSON.stringify(data) : 'Loading...'}</div>
</div>
);
}
Effect Order:
useEffect
to avoid layout thrashing or inconsistent rendering.useEffect
: Allows you to perform side effects in functional components. It accepts a function that runs after every render and can return a cleanup function.useEffect
hooks to handle different side effects separately.The useEffect
hook helps manage side effects in a declarative manner, making it easier to handle asynchronous operations, subscriptions, and other side effects in functional components.
@aCodeTutorials All Rights Reserved
privacy policy | about