Member-only story
Building TypeScript Types for the useReducer
Hook
The useReducer
hook is similar to the useState
hook, but where useState
works best for managing primitive values (e.g. strings, numbers, and boolean values), useReducer
excels at manipulating Objects with multiple properties.
// useState (from react docs):
const [name, setName] = useState('Taylor');
// useReducer (from react docs):
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
}
Whereas useState
directly sets the value it is managing with the second element returned by the hook, useReducer
provides a dispatch
function that can then be called with an action object. When dispatch
is called with an action, then a function defined outside the component will be called with the old state and the action. Typically, this function will contain a switch
statement that it will use to decide how to create a new state.
Our Example
A common use case is a Form where we are updating existing data. The Form might fetch that existing data based on the key(s) in the database (ids) and display that data. Then, the user would use the form fields to edit each property of the Object except the ids before submitting the result back to the backend for storage in the database.