Better Programming

Advice for programmers.

Member-only story

Building TypeScript Types for the Hook

7 min readAug 3, 2023

--

Person in dark clothes and a clear face mask kneeling on a reflective surface with a high-tech building lit in pink and blue in the background.
Photo by Drew Dizzy Graham on Unsplash

The hook is similar to the hook, but where works best for managing primitive values (e.g. strings, numbers, and boolean values), 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 directly sets the value it is managing with the second element returned by the hook, provides a function that can then be called with an action object. When 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 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.

--

--

Amy Blankenship
Amy Blankenship

Written by Amy Blankenship

Full Stack developer at fintech company. I mainly write about React, Javascript, Typescript, and testing.

Responses (1)