useEffect and synchronizing with external systems

Intermediate · 14 min

How useEffect's dependency array is actually compared, the bugs missing or extra dependencies cause, and when you don't need an effect at all.

Before thisThe component lifecycle, thought about through hooks

Web Dev Simplified · 14 min

useEffect and synchronizing with external systems

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • useEffect lets a component synchronize with something outside React's rendering model: the DOM, a subscription, a timer, browser storage, or a network request.
  • The dependency array is compared with Object.is on every render; if any entry differs from last render's value, React re-runs the cleanup from the previous effect and then the effect itself.
  • Objects, arrays, and functions are recreated on every render by default, so putting one in the dependency array without memoizing it causes the effect to re-run on every single render, not just when its contents actually change.
  • Leaving a value out of the dependency array that the effect body actually reads is the opposite bug: the effect keeps using a stale snapshot of that value from whenever it last ran.
  • React's own docs, and writers like Kent C. Dodds, push the framing 'you might not need an Effect' — a lot of effects people write are really just computing a value during render or responding to an event, neither of which needs useEffect at all.
  • The question to ask before writing an effect is not 'when should this run' but 'what, outside of React, needs to be kept in sync with this render'.

Effects exist for things React doesn’t manage

React renders your component, figures out what changed, and updates the DOM for you. That covers almost everything a typical component does — except for the handful of things that live outside that model: a setInterval, a window.addEventListener, a WebSocket connection, writing to localStorage, imperatively focusing an input. None of those get created or torn down by React re-rendering; something has to explicitly set them up and, later, explicitly tear them down. useEffect is that “something.”

function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);

  return <p>Connected to room {roomId}</p>;
}

Read this as a statement about what should always be true: “for whatever roomId currently is, there should be exactly one open connection to that room.” React makes that true by running the setup function after the render commits, and by running the cleanup function before it sets up the next connection (or before the component unmounts for good, if there’s no next render).

How the dependency array is actually compared

The second argument to useEffect isn’t a list of “things that should trigger a re-run” in some vague sense — it’s a precise contract. On every render, React takes the array you passed and compares each item, position by position, to the array from the previous render, using Object.is (which behaves like === for this purpose). If every pair is equal, the effect is skipped entirely for that render. If even one pair differs, React schedules the cleanup-then-setup sequence.

That Object.is detail is where the common bugs live.

// Bug: a new object every render, so the effect never stops re-running
function Profile({ userId }) {
  useEffect(() => {
    logPageView({ userId, page: "profile" });
  }, [{ userId, page: "profile" }]); // new object literal each render
}
// Fixed: depend on the primitive values the effect actually reads
function Profile({ userId }) {
  useEffect(() => {
    logPageView({ userId, page: "profile" });
  }, [userId]); // "profile" is a constant string, not a reactive value
}

The opposite mistake is leaving something out. If the effect body reads roomId but the dependency array is [], the effect only ever sees the roomId that was current the first time it ran — any later change to roomId re-renders the component but does not re-run the effect, so the connection quietly points at the wrong room. This is the “stale closure” bug, and it’s one of the main reasons the ESLint rule react-hooks/exhaustive-deps exists: it flags values your effect reads that aren’t in the dependency array, because in the overwhelming majority of cases leaving them out is a bug, not an optimization.

You might not need an Effect

Before reaching for useEffect, it’s worth asking whether you need an effect at all. React’s own documentation has a page by this exact title, and writers like Kent C. Dodds have made the same point for years: a lot of code written as an effect is one of two things in disguise.

The first is a derived value — something you can just compute while rendering:

// Unnecessary effect
const [fullName, setFullName] = useState("");
useEffect(() => {
  setFullName(`${firstName} ${lastName}`);
}, [firstName, lastName]);

// Just compute it
const fullName = `${firstName} ${lastName}`;

The second is event-response logic that belongs in the handler that caused it, not in an effect watching for the state that handler set:

// Unnecessary effect
useEffect(() => {
  if (submitted) {
    showToast("Saved!");
  }
}, [submitted]);

// Just do it where the event happens
function handleSubmit() {
  save();
  showToast("Saved!");
}

Both unnecessary-effect versions work, but they add an extra render cycle and make the data flow harder to trace. The rule of thumb: if you can compute it during render or do it directly inside the event handler that triggers it, you don’t need useEffect. Reach for it only when something genuinely needs to be kept in sync after the render, with something outside React.

What the video covers

Web Dev Simplified’s explainer is a tight walkthrough of useEffect’s mechanics: when it runs relative to rendering, how the dependency array is compared, and the standard external-system use cases — subscriptions, timers, fetches. It’s a reliable reference for the mechanics. It doesn’t explicitly use the “you might not need an Effect” framing from React’s docs, so that section above is this lesson’s own addition — watch the video for the mechanics, then come back here for when to skip the hook entirely.

Where this fits

Fetching data is the single most common reason people reach for useEffect, and it has its own set of pitfalls on top of everything here. The next lesson, data fetching in effects, walks through loading and error state, and sets up the problems that later push you toward a dedicated data-fetching library.

Check yourself

  1. 01What counts as an 'external system' that useEffect is meant to synchronize with?

    Anything outside React's own rendering and state model: the DOM directly, browser APIs like localStorage or the clipboard, a WebSocket or subscription, a timer, or a network request — anything React doesn't already manage by re-rendering.

  2. 02How does React decide whether to re-run an effect between two renders?

    It compares each entry in the dependency array to the corresponding value from the previous render using Object.is. If every entry is the same, the effect is skipped; if any entry differs, React runs the previous effect's cleanup function and then runs the effect again with the new values.

  3. 03Why can putting an object literal in a dependency array cause an effect to run on every render, even when its fields never change?

    Because `{}` creates a brand-new object reference on every render, and Object.is compares by reference for objects, not by value — so the dependency looks different every time even though the data inside it is identical.

  4. 04What does 'you might not need an Effect' mean in practice?

    It means a lot of code written as useEffect is really just a derived value that could be computed directly during render, or event-handling logic that belongs in the event handler that triggered it, and wrapping either of those in an effect adds an extra render and a layer of indirection that isn't needed.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark