Bitpath

Lesson 2 · Unit 03

Effects

Synchronising with the world outside React: dependencies, cleanup, stale closures, and effects you do not need.

13 exercisesabout 3 min

What you practise

  • Synchronising with something outside React, the dependency array, cleanup, the stale closure, effects you do not need

Try a question from this lesson

Pick one

A chat component must open a connection when it appears on screen. Rendering must stay pure, and no click causes "appearing". Where can the connecting code go?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Effects

useEffect synchronises a component with something outside React: a connection, a timer, a browser API. The setup function runs after the commit. The function it returns is the cleanup, which undoes the setup. The array lists the values the effect reads; React cleans up and sets up again only when one of them has changed.

TypeScript
useEffect(() => {
  // setup: runs after the commit
  const conn = connect(roomId);
  // cleanup: undoes the setup
  return () => conn.close();
}, [roomId]); // dependencies

Concept

Stale closures

An effect is created by a render and sees that render's props and state, like any handler. If it reads a value that is not in its dependency list, it keeps using the old one. Two cures: list every value the effect reads (the React linter checks this), or stop reading the value, for example with an updater function.

TypeScript
useEffect(() => {
  const id = setInterval(() => {
    // the updater needs no count
    setCount(c => c + 1);
  }, 1000);
  return () => clearInterval(id);
}, []);

10 more exercises in the app

  • 6× multiple choice
  • 1× match the pairs
  • 1× fill the blanks
  • 1× type the answer
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy