useState design
React provides a useState
hook to manage the state within function components. The following code example shows its common usage:
const Title = () => { const [state, dispatch] = useState(initialState) const onClick = () => { dispatch(newState) } return <button onClick={onClick} /> }
The useState
function takes an initialState
argument as the input argument and returns a state
object and a dispatch
function. The dispatch
function can be used to request a state change into a newState
object.
Have you ever wondered how React designs the useState
hook behind the scenes? Why does it return an array? How do we know if a new dispatch is successful or not? Most importantly, how can we be sure about the current state in each render?
To answer these questions, we will open up the engine and take a look inside. We will read through a stripped-down version of the source code to gain...