useEffect is a React Hook that lets you synchronize a component with an external system.
Parameters
() => (() => void) | void
required
The function with your Effect’s logic. Your effect function can optionally return a cleanup function.
- React will call your effect function after the component is added to the screen (after render)
- React will call your cleanup function (if provided) before the component is removed from the screen
- If dependencies change, React will first call the cleanup function with old values, then call the effect function with new values
Array<mixed> | void | null
The list of all reactive values referenced inside the effect code.
- If omitted, the effect runs after every render
- If
[](empty array), the effect runs only once (on mount) - If
[dep1, dep2], the effect runs when any dependency changes
Object.is.Returns
useEffect returns undefined.
Usage
Connecting to an external system
Some components need to stay connected to external systems while they’re displayed:Fetching data
In React 18+, consider using Suspense for data fetching, or use a data fetching library like React Query, SWR, or Redux Toolkit Query instead of manually managing loading states.
Subscribing to events
Running once on mount
Pass an empty dependency array to run the effect only once:Effect dependencies
- No dependencies
- Empty array
- With dependencies
Cleanup function
The cleanup function runs:- Before the effect runs again (if dependencies changed)
- When the component unmounts