-
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
countdoesn't change with asetInterval... - Why? -
How can you make it count? - Hint: Look at the squiggly line ;-)
Intermediate result:
-
Adding
countas dependency gives us CodeSandBox solution. Remaining problem: Interval is set and cleared every second. -
Note: With
countas dependency and constant setting and clearing ofsetInterval, thecountincreases because ofcountdependency. Really equivalent withsetTimeout, i.e. rougly equivalent tosetTimeout(() => setCount(count + 1), 1000);
Best solution
- Remove
countdependency viauseStatefunctional updater form: CodeSandBox: 15 - remove count dependency solution: Now interval is not set and cleared on every render.