Hooks and effects
Effects synchronize external systems
Use an Effect when rendering must start or update a connection to something React does not control.
An Effect synchronizes the rendered React state with a system React does not control.
Examples include:
- a browser media API
- a network connection
- a map or chart library
- an event subscription
- a timer that must follow component visibility
Ask one question before writing useEffect: Which external system needs to match which React values?
If there is no external system, you probably do not need an Effect.
Do not use an Effect to derive display data:
// Avoid
useEffect(() => {
setVisibleTasks(tasks.filter(task => !task.done))
}, [tasks])
Calculate it during rendering:
const visibleTasks = tasks.filter(task => !task.done)
The second version has one source of truth and avoids an extra render.
An action caused by a specific click also belongs in that event handler. Buying a product or submitting a form should not wait for an Effect to notice a state flag.
Effects are caused by rendering itself. A chat connection should exist whenever the chat room is rendered, regardless of which navigation event made it appear.
Review every Effect in a small component. Name the external system. If you cannot name one, try replacing the Effect with a render calculation or event handler.
Lesson completed