When working with React, one of the common needs is performing side effects like fetching data, updating the DOM, setting up subscriptions, or timers. In class-based components, we used lifecycle methods like componentDidMount
, componentDidUpdate
, and componentWillUnmount
.
In functional components, React’s useEffect
hook lets you handle these side effects efficiently.
What is useEffect
?
useEffect
is a React Hook that lets you perform side effects in function components. It runs after the component renders.
Basic Syntax:
import { useEffect } from 'react';
useEffect(() => {
// Side effect logic here
return () => {
// Cleanup code (optional)
};
}, [dependencies]);
How useEffect
Works
- The first argument is a function that contains the side effect.
- The second argument is an optional dependency array.
- The hook runs after every render, unless dependencies limit it.
Examples of useEffect
1️⃣ Run on Every Render (Not Recommended Usually):
useEffect(() => {
console.log('Component rendered or updated!');
});
2️⃣ Run Only Once (on Mount):
useEffect(() => {
console.log('Component mounted!');
}, []);
3️⃣ Run When Dependencies Change:
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count changed to ${count}`);
}, [count]);
4️⃣ Cleanup Example (Unmount or before rerun):
useEffect(() => {
const interval = setInterval(() => {
console.log('Interval running');
}, 1000);
return () => {
clearInterval(interval);
console.log('Interval cleared');
};
}, []);
Common Use Cases
- Fetching API data
- Setting up event listeners
- Managing timers or intervals
- Cleanup tasks like removing listeners
Common Mistakes
- Missing dependencies: Can cause stale data issues.
- Unnecessary effects: Running on every render without a dependency array.
- Forgetting cleanup: Can lead to memory leaks.
Conclusion
The useEffect
hook is powerful for handling side effects in React functional components. Mastering it helps in writing cleaner, more predictable code.
Example Full Component:
import { useEffect, useState } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(prev => prev + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <h1>Timer: {count}</h1>;
}
Summary Table
Dependency | When it Runs |
---|---|
None | After every render |
[] | Only once (component mount) |
[var] | When var changes |
Top comments (0)