Close the earlier lessons and work from the brief. This is a new problem, not a copy of a lab: decide for each effect whether it's needed at all, and what should restart it.
The brief
The starter is a notes box that autosaves every two seconds through a pretend
service, src/autosave.js. It looks as if it works, but watch the console
while you type: every keystroke logs autosave stopped and autosave
started. Someone who types steadily, a key at least every two seconds, is
never saved at all. Ticking Quiet saves restarts it too.
Change App.jsx so that:
- The word count is worked out during render. It needs no state and no effect.
- The autosave starts once, when the page appears, and nothing you type or tick restarts it.
- Each save still saves the latest note, and updates the status line to Last saved: and the note, unless Quiet saves is ticked. Quiet saves still save; they just don't change the status line.
Acceptance checks:
- Typing
hello worldshows Words: 2 straight away. - The console shows autosave started once, at the start. Typing and ticking Quiet saves log no autosave stopped.
- Two seconds after you stop typing
hello world, the console shows saved: hello world and the status reads Last saved: hello world. - With Quiet saves ticked, type more: the next save logs the new text, and the status line stays as it was.
App.jsxhas exactly oneuseEffect, and its dependency list is empty.
npm install and npm run dev. Hint 1: which effect, which tool?
Ask of each effect: does it keep something outside React in step? The word
count doesn't: it's calculated from note, which you already have. The
autosave does, so it stays an effect, but note and quiet are only needed at
the moment a save happens, not to decide when to start the service. That's the
job useEffectEvent did for the chat's Muted box.
Hint 2: a first step
Remove the word-count state and its effect first, and check Words still
updates. Then move the body of the autosave callback into a function made with
useEffectEvent, and have the effect's callback call it. What's left in the
effect's dependency list?
Show one solution
npm install and npm run dev. Check yourself
- Two components call the same custom hook. Do they share its state?
- Name three kinds of code that look like they need an effect but don't.
- What problem does
useEffectEventsolve?
Completion is saved in this browser only. It does not measure mastery.