Lesson 2 · Unit 03
Effects
Synchronising with the world outside React: dependencies, cleanup, stale closures, and effects you do not need.
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?
Correct answer
In an Effect: code React runs after the component is on screen
Why
The body runs on every render and must stay pure: connecting there would open a connection per render. A handler needs an event from the user. An Effect is caused by rendering itself: React runs it after the commit.
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.
useEffect(() => {
// setup: runs after the commit
const conn = connect(roomId);
// cleanup: undoes the setup
return () => conn.close();
}, [roomId]); // dependenciesConcept
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.
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.