Overview
TheuseEffect hook lets you perform side effects in functional components. It runs after the render is committed to the screen.
Signature
Parameters
A function containing the side effect code. This function may optionally return a cleanup function that will be called before the effect runs again or when the component unmounts.Signature:
() => void | (() => void)An optional dependency array. The effect only re-runs if one of the dependencies has changed.
- Omit to run on every render
- Empty array
[]to run only once on mount - Array with values to run when any value changes
Returns
This hook does not return a value.Usage Examples
Run Once on Mount
Run on Dependency Change
Cleanup Function
Return a cleanup function to clean up subscriptions, timers, or event listeners:Event Listeners
Multiple Effects
Separate different concerns into multiple effects:Rules and Behavior
- Runs after render - Effects are scheduled to run asynchronously after the browser has painted
- Cleanup runs before next effect - If an effect returns a cleanup function, it runs before the next effect executes
- Cleanup on unmount - All cleanup functions run when the component unmounts
- Dependency comparison - Uses strict equality (
!==) to compare each dependency - Must be called at top level - Don’t call
useEffectinside loops, conditions, or nested functions - Only in functional components - Cannot be used in class components
Dependency Array Behavior
| Dependencies | When Effect Runs |
|---|---|
| Not provided | Every render |
[] | Once on mount only |
[a, b] | When a or b changes |
Implementation Details
- Effects run asynchronously via
setTimeout(..., 0)after render - Dependencies are compared using strict equality (
!==) - Cleanup functions are stored per component instance and hook index
- Skips effect execution if dependencies haven’t changed
- Errors in effects are caught and logged to prevent crashes
- Checks if component is mounted before running effects