The useEffect hook is a fundamental hook in React that allows you to perform side effects in your functional components. Side effects can include tasks such as data fetching, subscriptions, and manually changing the DOM.
How to Use useEffect
1. Basic Usage
The useEffect hook takes two arguments:
- A function that contains the code for the side effect.
- An optional dependency array that specifies when the effect should run.
- The
useEffect
hook updates the document title based on thecount
state. - The effect runs after every render, but if you include a dependency array, the effect will only run when one of the dependencies changes.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// This effect runs after every render
document.title = `You clicked ${count} times`;
// Optional cleanup function to run when the component unmounts or before running the effect again
return () => {
document.title = 'React App';
};
}, [count]); // Dependency array: effect runs only when `count` changes
return (
You clicked {count} times
);
}
2. Dependency Array
- No Dependency Array: The effect runs after every render.
useEffect(() => {
// Effect code
}); // Runs after every render
- Empty Dependency Array: The effect runs only once, similar to
componentDidMount
in class components.
useEffect(() => {
// Effect code
}, []); // Runs only once after the initial render
- With Dependencies: The effect runs only when one of the specified dependencies changes.
useEffect(() => {
// Effect code
}, [dependency1, dependency2]); // Runs when `dependency1` or `dependency2` changes
3. Cleanup
If your effect requires cleanup, you can return a cleanup function from the effect. This function runs before the component unmounts or before the effect runs again.
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
// Cleanup function
return () => {
clearInterval(timer);
};
}, []); // Runs once after the initial render
In this example, clearInterval is called when the component unmounts or before the effect runs again to prevent memory leaks.
4. Fetching Data
useEffect is commonly used for data fetching operations.
import React, { useState, useEffect } from 'react';
function DataFetchingComponent() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, []); // Fetches data once after the initial render
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{JSON.stringify(data, null, 2)}
);
}
5. Using Effects with Multiple Dependencies
You can use multiple dependencies in the dependency array. The effect will run whenever any of these dependencies change.
useEffect(() => {
// Effect code
}, [dependency1, dependency2]); // Runs when either `dependency1` or `dependency2` changes
- Data fetching: Fetch data from APIs.
- Subscriptions: Set up subscriptions and clean them up.
- Manual DOM manipulations: Directly manipulate the DOM if necessary.
- Timers: Set up intervals or timeouts and clean them up.