React - useEffect Hook
Using the useEffect hook for side effects
The useEffect
hook is a powerful hook in React that allows you to perform side effects in functional components. Side effects include data fetching, subscriptions, and manually changing the DOM. The useEffect
hook combines the behavior of several lifecycle methods from class components, making it easier to manage side effects. This tutorial covers how to use the useEffect
hook for side effects in React functional components.
Key Points:
- The
useEffect
hook allows you to perform side effects in functional components. - It can be used for data fetching, subscriptions, and manually changing the DOM.
- The hook takes a function and a dependency array as arguments.
- The function can return a cleanup function to clean up side effects.
Basic Usage
The useEffect
hook takes a function as its first argument. This function is executed after the component renders. You can also pass a dependency array as the second argument to control when the effect runs.
// Basic usage of useEffect
import React, { useEffect, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Example;
Dependency Array
The dependency array controls when the effect runs. If you pass an empty array, the effect runs only once after the initial render. If you pass an array with dependencies, the effect runs whenever any of the dependencies change.
// Using dependency array in useEffect
import React, { useEffect, useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Example;
Cleaning Up Effects
The function passed to useEffect
can return a cleanup function. This cleanup function runs before the component unmounts or before the effect runs again, allowing you to clean up any side effects such as subscriptions or timers.
// Cleaning up effects with useEffect
import React, { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup function
}, []);
return <p>Seconds: {seconds}</p>;
}
export default Timer;
Fetching Data
The useEffect
hook is commonly used for fetching data from an API. You can use the fetch
API inside the effect and update the component state with the fetched data.
// Fetching data with useEffect
import React, { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array ensures the effect runs only once
return (
<div>
{data ? <p>Data: {data}</p> : <p>Loading...</p>}
</div>
);
}
export default DataFetcher;
Subscribing to Events
The useEffect
hook can also be used to subscribe to events. For example, you can subscribe to window resize events and update the component state accordingly. Remember to clean up the subscription in the cleanup function.
// Subscribing to events with useEffect
import React, { useEffect, useState } from 'react';
function WindowSize() {
const [size, setSize] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setSize(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize); // Cleanup function
}, []);
return <p>Window width: {size}</p>;
}
export default WindowSize;
Summary
In this tutorial, you learned how to use the useEffect
hook for side effects in React functional components. The useEffect
hook allows you to perform side effects such as data fetching, subscriptions, and manually changing the DOM. You learned about the dependency array, cleaning up effects, fetching data, and subscribing to events. Understanding the useEffect
hook is essential for managing side effects in modern React applications.