The useEffect hook lets you perform side effects in functional components.
useEffect runs after every render by default.
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}Control when the effect runs by providing a dependency array.
import { useState, useEffect } from 'react';
function Example({ id }) {
const [data, setData] = useState(null);
// Only re-run the effect if id changes
useEffect(() => {
const fetchData = async () => {
const response = await fetch(`https://api.example.com/posts/${id}`);
const data = await response.json();
setData(data);
};
fetchData();
}, [id]); // Dependency array
if (!data) return <div>Loading...</div>;
return <div>{data.title}</div>;
}Return a function from your effect to clean up resources.
import { useState, useEffect } from 'react';
function ChatRoom({ roomId }) {
useEffect(() => {
// Connect to the chat room
const connection = createConnection(roomId);
connection.connect();
// Cleanup function that runs before the effect runs again
// or when the component unmounts
return () => {
connection.disconnect();
};
}, [roomId]);
return <div>Connected to {roomId}</div>;
}An empty dependency array makes the effect run only once after the initial render.
import { useState, useEffect } from 'react';
function OnlyOnce() {
useEffect(() => {
// This runs once after the initial render
console.log('Component mounted');
return () => {
// This runs when the component unmounts
console.log('Component will unmount');
};
}, []); // Empty dependency array
return <div>I only log on mount and unmount</div>;
}