Why use UseEffect in React?
In React, the useEffect
Hook is used to perform side effects in function components. Side effects are tasks that interact with something outside the React component, such as fetching data, setting up subscriptions, or manually manipulating the DOM.
Here’s why and when you use useEffect
:
1. Managing Side Effects
- React components are declarative and focus on rendering UI based on state and props. However, some operations like fetching data or subscribing to events are imperative and considered side effects.
useEffect
allows you to perform these tasks without cluttering your rendering logic.
2. Lifecycle Management
- The
useEffect
hook effectively combines the behavior ofcomponentDidMount
,componentDidUpdate
, andcomponentWillUnmount
lifecycle methods in class components. - You can specify what the effect should do when the component.
- Mounts (initial load).
- Updates (state or props change).
- Unmounts (cleanup before the component is removed).
3. Dependency Management
- The second argument
useEffect
is a dependency array. It specifies when the effect should run. - Empty array
[]
: Run the effect only once, similar tocomponentDidMount
. - [dependencies]: Run the effect whenever the dependencies change.
- No array: Run the effect after every render, which is rarely efficient.
Common Use Cases for useEffect
- Fetching Data
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Runs only once after the component mounts
- Subscribing to Events
useEffect(() => {
const handleResize = () => console.log(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize); // Cleanup on unmount
}, []); // Runs once, subscribes on mount, and cleans up on unmount
- Updating DOM
useEffect(() => {
document.title = `New count: ${count}`;
}, [count]); // Updates the title whenever 'count' changes
- Timers and Intervals
useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup on unmount
}, []);
Summary
useEffect
is essential for handling side effects in functional components in a declarative, efficient, and readable way. It helps keep the logic clean and encapsulated while ensuring proper lifecycle management.