CodeSandBox: Counter in variables
Comments:
- Keep state in local variable (inside of component) or external variable (outside of component).
- Result: Component won't re-render.
Question: Why does the countOutside
value also change (with the state value) but inner countInside
does not?
Show Answer
Answer: The inner count
gets initialized (and set to 0
) on every render which is triggered by the state value.
CodeSandBox: useState with mutable vs. immutable state features broken and correct ways to update state.
- A new state value is created if the value passed to the setter function is not strictly equal the current value (referential equality in case of complex data types)
- Every successful state upate causes:
- The component function to be re-run
- A new state value to be returned by the
useState
hook
Note:
-
states are
const
(notlet
)! CodeSandBox: Also objects are entirely new objects, not just copied references (JS)) -
Questions: Why do the broken increment functions increase the value without updating the UI?
-
Answer: In case of the broken click handlers the
useState
hook's strict equality check returnstrue
thecount
value in the existing state variableobjectCount
does indeed change its value, but since it won't cause the component to re-render, bothuseEffect
hooks won't run and the function won't return a new UI to be rendered. See the appendix at the bottom for a code example concerning equality checks in JS. -
Note: Since the state value and the setter function are
const
values they can't be re-assigned.
TODO: Review this one: CodeSandBox: One state change causes all states to be new! (JS)
// current state
const obj1 = { val: 1 };
// Mutation: Change val: 1 to val: 2
obj1.val = 2
const obj2 = obj1
console.log(obj1 === obj2) // true
// New Object: Change val: 1 to val: 2
const obj3 = { val: 2 }
console.log(obj2 === obj3) // false