useState
We request React to:
- create and store a state variable
- give us a view on it (immutable view)
- give us a way to request change, though a dispatch function. It is up to React to acknowledge the request and update the document when it deems appropriate.
initial value and type
useState<number>(0)
receive the view and a dispatch function
const [count, setCount] = React.useState<number>(0)
call the dispatch function with a raw value
In its simplest form, the dispatch function expects a raw value:
setCount(1)
Note: if we use state we have in scope, it still resolves to a raw value. When calling it multiple times, we set the state to the same value (no effect)
setCount(count + 1)
// resolves to:
setCount(1)
queue state mutation
If we want to derive a value from the current state, we either:
- refer to the state value managed by React. We pass a callback, to which React passes the state value as it keeps track of.
- This pattern supports queuing state changes that resolve on state update. React correctly accounts for the queued mutations:
// note: count will increase by 2
setCount((count) => count + 1)
setCount((count) => count + 1)