Effects & synchronization
Try code in the playgroundUnderstand the concept
useEffect synchronizes a committed component with something outside React, such as a connection, timer or browser event listener. Its setup runs when relevant dependencies change, and cleanup ends the old synchronization. Effects are not the usual place to compute values already available during rendering.
Important ideas
-
Use it to synchronize with an external system, such as a subscription.
-
Clean up listeners, timers and connections before reconnecting or unmounting.
-
Do not use an effect just to calculate a value from current props or state.
-
Include reactive values used by the effect in its dependencies, and make cleanup undo the resource setup.
Example — effect cleanup:
import { useEffect, useState } from 'react';
function OnlineStatus() {
const [online, setOnline] = useState(true);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
update();
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return <span>{online ? 'Online' : 'Offline'}</span>;
}- Cleanup removes exactly the listeners setup added. Browser online status is only a network hint, not proof that your API is reachable.
Can you explain it without the notes?
When should I use useEffect?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
useEffect synchronizes a committed component with something outside React, such as a connection, timer or browser event listener. Its setup runs when relevant dependencies change, and cleanup ends the old synchronization. Effects are not the usual place to compute values already available during rendering.
Turn this concept into a clear answer.
- Explain the external system being synchronized; if there is none, reconsider whether an effect is needed.
Keep connecting the ideas.
Next lesson: Why does an effect run twice in development or loop forever?Adapted from 06_REACT_NEXTJS.md · “When should I use useEffect?”. Examples are study fragments; framework behavior can depend on your version.