Summary

In this lesson, you learned that:

  • An effect is code that React runs after it has rendered a component, for things outside React: the tab's title, timers, loading data, localStorage. You write it with useEffect(() => { ... }, [dependencies]), imported from "react" like useState.
  • The dependencies say when the effect runs: without the array, after every render; with [], once, when the component appears; with [day], at the start and whenever day changes. Every state variable and prop that the effect uses belongs in them.
  • The function that an effect returns is its cleanup. React calls it when the component disappears, and before it runs the effect again. An interval needs one: return () => clearInterval(id);, a function, not clearInterval(id) called at once.
  • An interval made in the first render keeps that render's values, so it changes state with the updater function: setSeconds((seconds) => seconds + 1).
  • Data is loaded in an effect, with an async function inside it that the effect calls. The data, loading and error in state tell the page what to show, and response.ok says whether the server sent the file.
  • To remember state, save it in an effect that depends on it, and read it with a function given to useState, which React calls only for the first render.

In the next lesson, Checkpoint: Stopwatch, you'll build a stopwatch whose interval runs in an effect: it starts, stops, goes back to zero and measures laps.

But first, a little practice: the lineup with a choice of stage, which loads the bands from a file and remembers the stage you chose.

Instructions

Load the bands from bands.json in an effect when the app starts, and show Loading… until they're there.

Remember the chosen stage: save stage in localStorage under the key stage whenever it changes, and read it when the app starts, with "all" when nothing is saved. Try it: choose the Tent and click Run.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

9/9

Next