r/reactjs • u/dance2die • Aug 01 '21
Needs Help Beginner's Thread / Easy Questions (August 2021)
Previous Beginner's Threads can be found in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! Weβre a friendly bunch π
Help us to help you better
Improve your chances of reply by
- adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- describing what you want it to do (ask yourself if it's an XY problem)
- things you've tried. (Don't just post big blocks of code!)
- Format code for legibility.
- Pay it forward by answering questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar! π
For rules and free resources~
Comment here for any ideas/suggestions to improve this thread
Thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
15
Upvotes
View all comments
Show parent comment
2
u/Nathanfenner Aug 23 '21
The entire block is closed over
started- and this instance ofstartedwill never change. So if it was originallyfalse, it will always befalse. If it was originaltrue, it will always betrue.Cleanup should be done as part, of, well, cleanup. You want to clear the interval when
startedis no longertrue; so you return the cleanup form the place where it's started:If it's
true, then you start the counter. Also, you return the cleanup function so that ifstartedever becomesfalse, the interval will automatically be halted.However, notice that
timerSecondsis being used inside thisuseEffectcallback, but it's not in your dependency array:[started]. This is probably a problem. Yes, the interval will run every second, but you'll just keep setting it to the same value every time:timerSeconds - 1, wheretimerSecondsis whatever value it originally had.You should enable the React eslint hooks plugin, so that you get a warning about this likely mistake.
There are two ways to fix this:
First, you could add
timerSecondsto your dependency array. This means that once it's changed by the counter, the cleanup will run and it will start again. For this reason, if you do it this way, it probably makes more sense to usesetTimeoutinstead ofsetIntervalsince it would only ever run once anyway.Second, you could instead use a form of update that doesn't require closing over the original
timeSecondsvalue. Using a functional update you can instead callsetTimerSeconds(currentValue => currentValue - 1); this function will be used to update the value, which doesn't depend on knowing what the current value is. So you can dispatch this once a second with no problems, without updating your dependency array.