useEffect: Synchronizing with External Systems

An Effect is for synchronizing a component with something outside React: subscriptions, timers, browser APIs, imperative widgets, or network interactions when appropriate.

Do not use an Effect merely because a value can be calculated from other state. If fullName is derived from firstName and lastName, calculate it during render. An unnecessary effect creates an extra render and introduces synchronization complexity.

An effect has a setup phase and optionally a cleanup phase. Cleanup should undo the external subscription, timer, listener, or resource established by the setup.

Effect Lifecycle
Subscription cleanup
useEffect(() => {
  const connection = connect(roomId);
  connection.on("message", handleMessage);

  return () => {
    connection.off("message", handleMessage);
    connection.disconnect();
  };
}, [roomId, handleMessage]);
💡 When the room changes or the component unmounts, cleanup prevents the previous connection from remaining active.
Key Takeaways
  • Effects synchronize with external systems.
  • Cleanup must reverse setup work.
  • Do not use effects for ordinary derivations.
Knowledge Check

Which is the best reason to use `useEffect`?