Repository navigation
useEffect
vinibiavatti1 edited this page Sep 28, 2026
·
3 revisions
Synchronizes a component with an external system (e.g., browser APIs, networks, timers). It runs asynchronously after the component has rendered to the screen.
Runs on every single render when the dependency array is completely omitted.
import { useEffect } from 'react';
export const MyComponent = () => {
useEffect(() => {
console.log('Component rendered or updated');
});
// ...
};Runs only once when the component first mounts to the DOM by passing an empty dependency array.
import { useEffect } from 'react';
export const MyComponent = () => {
useEffect(() => {
fetch('/api').then(...);
}, []);
// ...
};Runs on mount and re-runs whenever any value inside the dependency array changes.
import { useEffect } from 'react';
export const MyComponent = () => {
useEffect(() => {
fetch('/api').then(...);
}, [dep1, dep2, ...]);
// ...
};Cleans up side effects (like sockets, timers, or subscriptions) by returning a cleanup function from the setup callback.
import { useEffect } from 'react';
export const MyComponent = () => {
useEffect(() => {
const socket = ...
return () => socket.close();
}, []);
// ...
};This table maps traditional Class Component lifecycle methods to their modern Functional Component equivalents using useEffect (and React.memo for update checks).
| Class Component | Functional Component |
|---|---|
componentDidMount |
useEffect(() => { ... }, []) |
componentDidUpdate |
useEffect(() => { ... }, [dep1, dep2, ...]) |
componentWillUnmount |
useEffect(() => { return () => { ... } }, []) |
shouldComponentUpdate |
React.memo(Component, arePropsEqual) |
- Home
- Functional Components
- Props
- Fragments
- Memoization
- Forward Ref
- Portals
- Suspense
-
Hooks
- State
- Context
- Effect
- Ref
- Performance
- Concurrent
- Form
- Utility
- Custom Hooks