Scenarios: Every click counts (e.g. in a game or a real-time trading app). Even if the server lags, I want every interaction to be counted.
We look at two cases in which time lags of asynchronous actions (mostly API calls) can cause issues.
Problem: CodeSandBox: Async setting of state (problem) - observe the issue
- Closure in action:
countis frozen at the value of the first render. - Setter of state is in an asynchronous function (
setTimeout).
Non-ideal solution: CodeSandBox: Async setting of state (non-ideal solution)
Solution: CodeSandBox: Async setting of state with functional updater form
- functional updater form (
c -> c + 1) of useState hook.
Let's look at this similar case:
- Problem (number): CodeSandBox: async retrieval of state - observe the issue
Problem description:
- Issue:
countgets frozen and subsequent changes during the asyncsetTimeoutcall are ignored in alert. - Can this issue be solved with the updater function? - Try it!
Task: What is going on in here?
These CodeSandBoxes contain the solution without explanations:
count: number: CodeSandBox: async retrieval of state (number)
Solution: Closure in action!
These CodeSandBoxes contain explanations:
-
Why?: State values are new on every render (primitive data types and objects alike are
constvalues) -
The CodeSandBox: Problem also exists for
countstored in an object. -
Learn more about the
useRefhook in theuseRefhook section and via this CodeSandBox: ref vs. state vs. local variable (JS) -
Task with
{ count: number }object: CodeSandBox: async retrieval of state (object) -
Solution with
{ count: number }object: CodeSandBox: async retrieval of state with helper variable (object)