Tech Interview RoomStudy guides

React

Explain useEffect: dependencies, cleanup, and when you should not use it.

Intermediate · 2 min read · Lesson 4 of 14 in React

useEffect(setup, deps) synchronises a component with something outside React: a subscription, a timer, a non-React widget, a network connection, the document title.

How it runs

  • After React commits the render to the screen (it does not block painting).
  • Again whenever a value in the dependency array changes (compared with Object.is). [] means only on mount; no array means after every render.
  • The cleanup function returned from setup runs before the next run and on unmount.
  • In development, Strict Mode mounts, unmounts and mounts again to prove your cleanup works.

Dependency rules

List every reactive value the effect reads (props, state, values derived from them). Do not silence the react-hooks/exhaustive-deps lint rule; instead move objects or functions inside the effect, or use functional updates.

You might not need an effect

  • Derived data: compute during render (const total = items.reduce(...)), with useMemo if expensive, instead of an effect that sets state.
  • Responding to a user event: do it in the event handler.
  • Resetting state when a prop changes: use a key.
  • Fetching data: prefer a data library (TanStack Query, SWR), a framework loader, or use() with Suspense. If you do fetch in an effect, handle race conditions.

Example

jsx
function ChatRoom({ roomId }) {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on('message', m => setMessages(prev => [...prev, m]));
    connection.connect();
    return () => connection.disconnect();     // runs when roomId changes or on unmount
  }, [roomId]);

  return <MessageList messages={messages} />;
}

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then(r => r.json())
      .then(setUser)
      .catch(e => { if (e.name !== 'AbortError') throw e; });
    return () => controller.abort();          // ignore the stale response
  }, [userId]);
  return user ? <h2>{user.name}</h2> : <Spinner />;
}

Follow-up questions interviewers ask

Try answering each one before you open it.

What is the difference between useEffect and useLayoutEffect?

useLayoutEffect runs synchronously after the DOM is updated but before the browser paints. Use it only to measure layout (an element's size or position) and adjust before the user sees a flicker, such as positioning a tooltip. It blocks painting, so default to useEffect.

What does useEffectEvent solve?

Sometimes an effect needs to read the latest value of something (for example a theme for a notification) without re-running when it changes. useEffectEvent (stable in React 19.2) wraps that logic in a function that always sees fresh props and state but is not a dependency, so the connection is not torn down when the theme changes.