-
Heuristic to handle values properly with hooks. Do the following (in order):
- Put all dependencies into the dependency array (don't cheat!)
- Now think: Can value be removed without changing the result?
-
In CodeSandBox: count in intervals the
count
doesn't change with asetInterval
... - Why? -
How can you make it count? - Hint: Look at the squiggly line ;-)
Intermediate result:
-
Adding
count
as dependency gives us CodeSandBox solution. Remaining problem: Interval is set and cleared every second. -
Note: With
count
as dependency and constant setting and clearing ofsetInterval
, thecount
increases because ofcount
dependency. Really equivalent withsetTimeout
, i.e. rougly equivalent tosetTimeout(() => setCount(count + 1), 1000);
Best solution
- Remove
count
dependency viauseState
functional updater form: CodeSandBox: 15 - remove count dependency solution: Now interval is not set and cleared on every render.