
what is useEffect() ?
useEffect is a React Hook that allows functional components to perform side effects, such as data fetching, subscriptions, or manually updating the DOM. It's similar to componentDidMount, componentDidUpdate, and componentWillUnmount in class components. It lets you synchronize a component with an external system.
What is a Side Effect?
A side effect is anything that happens outside the component rendering, like:
- Fetching data from an API
- Updating the DOM directly
- Starting a timer
- Subscribing/unsubscribing to events
Basic Syntax
useEffect(() => {
// code to run after render (side effect)
}, [dependencies]);
- The function inside runs after the component renders.
- The [dependencies] array controls when it runs.
Example: Run on Every Render
This runs every time the component renders.
useEffect(() => {
console.log('Component rendered');
});
Example: Run Only Once (on mount)
The empty array [] means run only once (like componentDidMount in class components).
useEffect(() => {
console.log('Component mounted');
}, []);
Example: Re-run When Value Changes
Runs only when the count value changes.
useEffect(() => {
console.log('Count changed:', count);
}, [count]);
Example: Clean Up (like unmount)
useEffect(() => {
const timer = setInterval(() => {
console.log('tick');
}, 1000);
return () => {
clearInterval(timer); // clean up on unmount
};
}, []);
Real-Life Example: Fetch Data
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
Summary
Feature | Description |
---|---|
useEffect() | Handles side effects in function components |
Empty [] | Runs once on mount |
[dependency] | Runs when value in array changes |
Return a function | For cleanup (likecomponentWillUnmount) |