React · Chapter 14 of 26
Effects
By the end of this chapter you can keep something outside React in step with your component, with useEffect: the browser tab's title, a timer, a key pressed anywhere on the page, a live connection. You can say when an effect runs (after React has updated the page), choose its dependency list (none, [], or the values it reads), write the cleanup that undoes it, and explain why StrictMode runs every effect twice in development. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Effects and data
- 4 tasks
- React
- In the all labs plan
The first 2 chapters of React are free. This one comes with the all labs plan.
Why you need this
Everything you have written so far happens inside React: a component gets props and state and returns JSX, and an event handler changes state when someone clicks. Pune 52's show page needs four things that are outside React, and none of them is a click:
- The browser tab should say Pune 52 · Parda. Sayali opens twenty tabs of shows when she plans a weekend, and every one of them says Parda.
- The hold timer: Parda holds your seats for 10 minutes while you pay, and the page must count down by itself, once a second, from the moment the timer appears.
- Ira's dialogs must close when you press Escape, wherever the focus is, which means listening to the whole window, not to one button.
- The live seat count comes from Parda's feed, which sends a number every two seconds while the page is open, and must be closed when it is not.
Rendering cannot do these (it must be pure, chapter 6), and an event handler runs only when the user does something. React has a third place for code: an effect.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
ShowTitle.jsx: the title in the browser's tab
Make ShowTitle({ show }) return a heading, h2, with the show's title (Pune 52), and keep document.title, the text on the browser's tab, in step with it: after ShowTitle is on the page, document.title is Pune 52 · Parda (a middle dot with a space on each side); when ShowTitle gets another show, it becomes The Tiffin Thief · Parda; and when ShowTitle leaves the page, it goes back to Parda.
Change document.title in an effect, never while rendering: the Check first renders ShowTitle on a server, where effects never run, and document.title must not change there. Then it renders it under StrictMode, gives it another show, and removes it. The strip at the top of the Preview shows the frame's document.title.
- Task 2
HoldTimer.jsx: ten minutes to pay
Make HoldTimer({ seconds }) count down once a second from seconds, 600 when it is not given, to 0. It shows one paragraph: Seats held for 10:00, then 9:59, 9:58 and so on to 0:01, as the minutes, a colon and always two digits of seconds (1:05, 0:09). At 0 it shows Time is up. Your seats are released. instead, and nothing else.
No timer may be left running when time is up, or when HoldTimer leaves the page, and exactly one timer runs while it counts. The Check uses fake timers under StrictMode: it reads the page after each second, counts the timers that are running after the first render, after 59 seconds, at 0 and after HoldTimer leaves, and also renders it with seconds 65.
- Task 3
Dialog.jsx: a dialog that closes on Escape
Make Dialog({ title, children, onClose }) return an element with role="dialog" and aria-label={title} that holds a heading, h2, with the title; its children; and a button Close, which calls onClose.
While the dialog is on the page, pressing Escape anywhere calls onClose() once; other keys do nothing. When the dialog leaves the page, Escape does nothing any more. Listen for keydown on window in an effect, and remove the same function in its cleanup: the Check renders Dialog under StrictMode, where a listener that is never removed is added twice and calls onClose twice. When the parent gives Dialog a new onClose, Escape must call the new one, once.
- Task 4 · interview question
Interview: SeatFeed.jsx, the feed that connects twice
SeatFeed({ showtimeId }) shows the seats left, live, from connect(showtimeId, onSeatsLeft) in live.js, which calls onSeatsLeft with a number every 2 seconds and returns a function that disconnects. Its effect never disconnects: the Preview's console says feed: connected to T0051 twice, and after switching to Mon 9 Nov the count jumps between two showtimes' numbers.
Fix the effect so that there is exactly one open connection, to showtimeId, also under StrictMode; when showtimeId changes, the old one is disconnected and one to the new showtimeId is opened; a new count does not open a new connection; and when SeatFeed leaves the page, nothing stays connected. It shows one paragraph: Waiting for the feed... before the first message, and Seats left: 85 after it. The Check gives SeatFeed its own live.js and counts the connections that are still open.
Rukhsana will ask: why does my effect run twice?
What you will learn
- Why not in render: code there runs at every render, more times than you think.
- useEffect(setup, deps): code that runs after React has updated the page.
- The dependency list: none (after every render), [] (once, when it appears), [a, b] (when a or b changed).
- Cleanup: a function the effect returns, to undo what it did.
- StrictMode runs effect, cleanup, effect on mount in development, to check the cleanup.
- The rule of dependencies: every value from the component that the effect reads goes in the list.
More in Effects and data
Build "Effects" yourself
Parda sells tickets for Pune's own cinemas and stages, and its booking page broke on opening night. You rebuild it in React. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of React are free. This one comes with the all labs plan.