Using the useReducer Hook
Before we can start utilizing the second hook that React offers for state management, let's go through the fundamental difference as to how useState
and useReducer
approach state transitions (rather, how we can set a new state). With useState
, we concentrate on how to transition each individual piece of state. With useReducer
, we concentrate instead on the entirety of the state and setting logical rules for state manipulation.
Now, take a look at this pseudocode (this is provided as an example; don't try to run this):
const Thermostat = () => { const [temperature, setTemperature] = React.useState(20); return ( <> <div>current temperature is {temperature}</div> <button onClick={() => do(INCREMENT)}>increase temperature</button> <button onClick={() => do(DECREMENT)}>decrease temperature</button> <...