Skip to content
FrontDepth, Home

Back to the topic

Practice: useEffect: dependencies and cleanup

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

4 predict-output · 3 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    This is a plain-JS simulation, not React: createEffect() models one useEffect(setup, [roomId]). After each "render", commit() compares the dependencies with Object.is; if they changed, it runs the previous cleanup and then the new setup. What does it log?

    JavaScript
    function createEffect() {
      let prevDeps;
      let cleanup;
      return {
        commit(deps, setup) {
          const changed = prevDeps === undefined || deps.some((d, i) => !Object.is(d, prevDeps[i]));
          if (!changed) return;
          if (cleanup) cleanup();
          cleanup = setup();
          prevDeps = deps;
        },
        unmount() {
          if (cleanup) cleanup();
        },
      };
    }
    
    const effect = createEffect();
    
    function ChatRoom(roomId) {
      console.log("render " + roomId);
      effect.commit([roomId], () => {
        console.log("connect " + roomId);
        return () => console.log("disconnect " + roomId);
      });
    }
    
    ChatRoom("general");
    ChatRoom("general");
    ChatRoom("travel");
    effect.unmount();
  2. Open questionJunior

    What is useEffect for, and when do its setup and cleanup run?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    A plain-JS simulation of how React decides whether an Effect must re-run: each dependency is compared with its previous value using Object.is, and nextDeps === undefined stands for an Effect with no dependency array. What does it log?

    JavaScript
    function depsChanged(prevDeps, nextDeps) {
      if (prevDeps === undefined || nextDeps === undefined) return true;
      return nextDeps.some((dep, i) => !Object.is(dep, prevDeps[i]));
    }
    
    const options = { roomId: "general" };
    
    console.log(depsChanged(["general"], ["general"]));
    console.log(depsChanged([{ roomId: "general" }], [{ roomId: "general" }]));
    console.log(depsChanged([options], [options]));
    console.log(depsChanged([NaN], [NaN]));
    console.log(depsChanged([0], [-0]));
    console.log(depsChanged([], []));
    console.log(depsChanged(["general"], undefined));
  4. Predict the outputMiddle

    A plain-JS simulation of an autosave Effect: each render(text) is a render of the editor, and its "Effect" starts a timer that saves text, with dependencies [] or [text]. After three renders, tick() fires every active timer once. What does it log?

    JavaScript
    const timers = new Map();
    let nextId = 1;
    const setTimer = (fn) => {
      timers.set(nextId, fn);
      return nextId++;
    };
    const clearTimer = (id) => timers.delete(id);
    const tick = () => timers.forEach((fn) => fn());
    
    function runEditor(withTextDependency) {
      timers.clear();
      const saved = [];
      let created = 0;
      let prevDeps;
      let cleanup;
    
      function render(text) {
        const deps = withTextDependency ? [text] : [];
        const changed = prevDeps === undefined || deps.some((d, i) => !Object.is(d, prevDeps[i]));
        if (!changed) return;
        if (cleanup) cleanup();
        const id = setTimer(() => saved.push(text));
        created += 1;
        cleanup = () => clearTimer(id);
        prevDeps = deps;
      }
    
      render("H");
      render("Hi");
      render("Hi!");
      tick();
      return "saved " + saved.join(",") + ", created " + created + ", active " + timers.size;
    }
    
    console.log(runEditor(false));
    console.log(runEditor(true));
  5. Open questionMiddle

    How does the dependency array work, and how can it lead to infinite render loops and stale closures?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  6. Predict the outputSenior

    A plain-JS simulation of a search Effect with dependencies [query]: runEffect(query) runs the previous cleanup and then "fetches" with a promise that the code resolves by hand. The user types "re", then "react", and the response for "react" arrives before the one for "re". What does it log, without and with the ignore flag?

    JavaScript
    function deferred() {
      let resolve;
      const promise = new Promise((r) => {
        resolve = r;
      });
      return { promise, resolve };
    }
    
    async function search(useIgnore) {
      let shown = "nothing";
      const requests = {};
      let cleanup;
    
      function runEffect(query) {
        if (cleanup) cleanup();
        let ignore = false;
        requests[query] = deferred();
        requests[query].promise.then((result) => {
          if (!useIgnore || !ignore) shown = result;
        });
        cleanup = () => {
          ignore = true;
        };
      }
    
      runEffect("re");
      runEffect("react");
      requests.react.resolve("results for react");
      requests.re.resolve("results for re");
      await new Promise((r) => setTimeout(r, 0));
      return shown;
    }
    
    console.log(await search(false));
    console.log(await search(true));
  7. Open questionSenior

    How do you fetch data in an Effect without race conditions, and when should you avoid fetching in an Effect at all?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.