ReactInterview preparation
Intermediate·Concept·2 min read

When should I use useEffect?

Practice this question

Definition:

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.

Key points:

  • 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:

jsx
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.

Interview point:

  • Explain the external system being synchronized; if there is none, reconsider whether an effect is needed.
Adapted from 06_REACT_NEXTJS.md · “When should I use useEffect?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.