The useEffect
Hook in React is a function that lets you perform side effects in functional components. A side effect is anything that affects something outside the scope of the function being executed, such as data fetching, subscriptions, or manually changing the DOM. Essentially, it’s a way to tell React that your component needs to do something after rendering.
The useEffect
Hook is a great tool for managing the lifecycle of your components, allowing you to perform actions at specific points in time, like when the component first mounts, when it updates, or when it unmounts.
How It Works
useEffect(setup, dependencies)
1. Running an Effect on Every Render
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// This effect runs on every render
console.log(`The count is: ${count}`);
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
2. Running an Effect Only Once (on Mount)
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// This effect runs only once, when the component mounts
fetch('https://api.example.com/data')
.then(response => response.json())
.then(json => setData(json));
}, []); // The empty array ensures this effect runs only once
return (
<div>
{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : <p>Loading...</p>}
</div>
);
}
3. Running an Effect When Dependencies Change
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
// This effect runs whenever 'userId' changes
console.log('Fetching user data...');
fetch(`https://api.example.com/users/${userId}`)
.then(response => response.json())
.then(json => setUser(json));
}, [userId]); // The effect re-runs when userId changes
return (
<div>
{user ? <h1>User: {user.name}</h1> : <p>Select a user</p>}
</div>
);
}
4. Cleanup Function
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);
// This is the cleanup function
return () => {
clearInterval(intervalId);
console.log('Timer cleaned up!');
};
}, []); // Empty dependency array means this effect runs once on mount
return <h1>Seconds: {seconds}</h1>;
}