TheuseEffecthook is one of the most powerful and frequently used hooks in React. It allows you to performside effectsin functional components.
What are Side Effects?
Side effects are operations that affect somethingoutsideof the component's rendering. Examples include:
- Data Fetching:Making API calls
- DOM Manipulation:Direct DOM changes
- Setting up Subscriptions:Websockets, timers
- Logging:Analytics or debugging
- Updating Document Title:Changing the browser tab title
React components should be predictable—taking props and state as input and returning UI as output. Since side effects are inherently less predictable,useEffecthelps manage them safely.
Basic Usage
TheuseEffecthook takes two arguments:
- A function:Runs after the component renders
- An optional dependency array:Controls when the effect re-runs
import React, { useState, useEffect } 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>
);
}
Because no dependency array is provided, this effect runs aftereveryrender.
The Dependency Array
The dependency array determines whenuseEffectexecutes.
[](Empty Array):Runs only once after the initial render.
useEffect(() => {
console.log('Component mounted!');
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
}, []);
[variable]:Runs on initial render and whenever the variable changes.
useEffect(() => {
console.log('Count changed to:', count);
}, [count]);
- No Dependency Array:Runs after every render (use with caution).
Cleanup Function
Some side effects require cleanup to prevent memory leaks. You can return a cleanup function fromuseEffect.
useEffect(() => {
const subscription = someExternalService.subscribe(data => {
console.log('Received data:', data);
});
return () => {
subscription.unsubscribe();
console.log('Component unmounted - subscription unsubscribed');
};
}, []);
The cleanup function runs:
- Before the component unmounts
- Before the effect re-runs
Common Use Cases
- Fetching Data:Use
[]to fetch once - Updating the DOM:Prefer React when possible
- Event Listeners:Always clean them up
- Timers:Clear intervals and timeouts
- Logging:Analytics and debugging
Important Considerations
- Avoid infinite loops:Watch dependency changes carefully
- Performance:Keep effects lightweight
- Readability:One effect per concern
- Rules of Hooks:Call
useEffectonly at the top level of components or custom hooks
MasteringuseEffectand its dependency array allows you to build predictable, efficient, and maintainable React applications.