How to use UseReducer with TypeScript
BCiriak Avatar
by BCiriakDEC 02, 2022 | 15 min read

React useReducer with TypeScript

UseReducer and TypeScript is a good combo to tackle more complex component state problems. But how do they work together?


useReducer hook is one of Reacts API features that helps us manage state in React components. It has been added to react in version 16.8 along with other hooks.

Managing state with useReducer

You can think of useReducer as older brother of useState. Older meaning it can handle more complicated things.

Following is a diagram of simple Todo App that we will reconstruct with useReducer.

Simple Todo App with useReducer diagram

On the left, we have mock of the app and on the right is useReducer with its 4 main parts, state, dispatch, action and reducer.

State

Well, state is the container that holds our information. This state can hold much more complex data than useState. Not that useState can't hold complex data, but its use is not suited for such a complex data.

For managing more complex state make sure to look at Context API with useReducer and TypeScript.

Dispatch

Dispatch is a special function given to us by useReducer and it is some kind of messenger between our UI and state. In this example we could have different changes that we would want to do to our state. Like adding a todo or removing todo. Dispatch is the one carrying the message what we want to do with our state. The message would be action in our case.

Action

Action is plain object that specifies what we want to do with our state. Here is an example of adding a todo action:

example.tsxtypescript
1{
2	 type: "ADD_TODO",
3	 todo: "Buy Milk"
4}

So dispatch is the messenger and action is the message.

Reducer

Now we come to the last piece of useReducer, the brains. Reducer itself is where all of the logic happens. Reducer is pure function, that looks at action and decides how to change state. It has access to currentState and that is how we update it. But we never mutate state in reducer, we just copy it and return new state.

Back to the Todo App

Looking at the previous picture, we see that there is already some initial state, todos array. If we want to add a Todo to this array, we would click on Add Todo button, which would fire useReducers' dispatch function with appropriate action. In this case "ADD_TODO", and it would be handled by reducer, which would update the state. React would look at the state, see the change and re-render our UI.

Simple Todo App with useReducer diagram 2

Alright, to better understand how useReducer works, especially with TypeScript, let's build this simple app.

Learn more about advantages of TypeScript.

Clean React TypeScript app with Vitejs

I am gonna create barebones React TypeScript app with Vitejs, an amazing tool for creating Front-end applications.

If you don't know Vite, have a look at Create React App With Vite.

Note:

To create React app with TypeScript, make sure to use this command: 'npm create vite@latest my-react-app --template react-ts'

First thing I will do, is to remove all the noise from App.tsx and get to this point:

App.tsxtypescript
1function App() {
2  return (
3    <div>
4      <h1>Todos</h1>
5    </div>
6  )
7}
8
9export default App

I also don't like the dummy styling included with Vite, so I just removed everything from index.css. Now if we run npm run dev, we should be all set.

Adding useReducer

Let's add useReducer to our app. And we will do this in a silly way, so that we can understand it a little better.

To initialise useReducer, we need to supply 2 arguments to this hook. Reducer and initial state. As I mentioned before, reducer is pure function returning state. initialState is object holding our state/data.

App.tsxtypescript
1import { useReducer } from 'react'
2
3  const initialState = {
4    todos: [],
5  }
6
7  const reducer = (state: any, action: any) => {
8    return state
9  }
10
11  function App() {
12  const [state, dispatch] = useReducer(reducer, initialState)
13
14    return (
15      <div>
16        <h1>Todos</h1>
17        <pre>{JSON.stringify(state, null, 2)}</pre>
18      </div>
19    )
20}
21
22export default App

First, we imported the useReducer hook itself from 'react'. We created initialState object with one key todos, initialised to an empty array. Underneath is our dummy reducer, doing only one thing right now, returning state. It also has 2 arguments (for now typed as any), first one is the actual state that we have access to in reducer and second is our action.

Inside our App component we initialise the useReducer with our reducer and initialState.

Last little detail is the pre tag, to display our state.

Note:

JSON.stringify is function to, well, make string out of JSON. But we can nicely format the outputted string, by supplying 2 more arguments. Second argument is 'replacer' and this can be function, array or null, used in case we want to somehow manipulate the output, e.g. we don't want some of the properties to be shown in the JSON string. And the last one is 'space', meaning how we want to indent and line break characters, for better readability.

Using our useReducer to add a Todo

First of all, we need a button to be able to add a Todo.

App.tsxtypescript
1<button onClick={() => dispatch({ type: 'addTodo', payload: 'Buy Milk' })}>
2  Add Todo
3</button>

We are using dispatch function given to us by the hook and supplying it with hardcoded action object for now. Don't worry, we will improve this solution.

The only thing missing is now some logic in reducer that will handle the action and update state accordingly.

App.tsxtypescript
1const reducer = (state: any, action: any) => {
2  switch (action.type) {
3    case 'addTodo':
4      let newTodos = [...state.todos, action.payload]
5      return { ...state, todos: newTodos }
6    default:
7      throw new Error(`Unhandled action type: ${action.type}`)
8  }
9}

For those of you familiar with Redux, this syntax in reducer should be very simple to understand. switch statement is perfect for this situation, but you could very well use if else statement to make this logic work.

Right now we have 2 options how the switch can go. Default state will throw error if the action.type will be unknown, and addTodo will add new todo to our state. Remember, we don't want to mutate the state, that is why we first copy the todos from current state by destructuring it ...state.todos and then we simply add our new todo from action.payload to that new array.

Last thing to do, is to copy our whole state, again by destructuring the state object and overwriting the todos with our newTodos array.

We should now be able to add our hardcoded todo to the state, by clicking the Add Todo button.

Improving useReducer with typing

Looking at our App, besides those two any parameters in the reducer function, it is just regular old JavaScript component. It would be shame not to use the power of TypeScript, so let's get into it.

Good place to start is our state. Let's give our state proper types so that we can get some benefits of TypeScript:

App.tsxtypescript
1type Todo = {
2  id: number
3  description: string
4}
5
6type State = {
7  todos: Todo[]
8}
9
10const initialState: State = {
11  todos: [],
12}

Here we created 2 simple types, Todo and State. Now we know exact structure of our todo list. Every todo needs to have an id and a description, and our todos array is array of those todos.

In a same way we can add types to the reducer function.

App.tsxtypescript
1const reducer = (
2  state: State,
3  action: { type: string; payload: Todo }
4): State => {
5  switch (action.type) {
6    case 'addTodo':
7      let newTodos = [...state.todos, action.payload]
8      return { ...state, todos: newTodos }
9    default:
10      throw new Error(`Unhandled action type: ${action.type}`)
11  }
12}

Pretty simple, we just got rid of those any types, which by the way are never a good sign. You should never use those. Also, check out the return type of the reducer. It always returns State.

With this change, we also need to update the dispatch function call in our onClick. It is just a simple change of switching the payload to the correct type:

App.tsxtypescript
1<button
2  onClick={() =>
3    dispatch({
4      type: 'addTodo',
5      payload: { id: 123, description: 'Buy Milk!' },
6    })
7  }
8>
9  Add Todo
10</button>

Awesome, with these changes we know what to expect in our action, and in our state.

Adding more data to the state

Having hardcoded value as a Todo is truly not very useful. Let's change that by adding an input field, and handle all of it with our useReducer. But before we do that, we can improve our reducer by removing plain strings from our cases.

It is great practice to extract usages of plain strings into constants, this way we will not make simple typo and introduce bug.

App.tsxtypescript
1...
2const ADD_TODO = 'addTodo'
3...
4switch (action.type) {
5	 case ADD_TODO:
6...

As we will add more types of actions, we will just add corresponding constants.

Back to the input for our todo.

App.tsxtypescript
1<input
2  type="text"
3  value={state.newTodoValue}
4  onChange={(e) =>
5    dispatch({
6      type: UPDATE_VALUE,
7      payload: { description: e.target.value },
8    })
9  }
10/>

This is how the input looks like. We are handling its value with our state, which we will add to initialState in just a second. Another thing is, the UPDATE_VALUE. This means we will need to also update our reducer to handle this action case.

App.tsxtypescript
1...
2const ADD_TODO = 'addTodo'
3const UPDATE_VALUE = 'updateValue'
4...
5type State = {
6	 todos: Todo[]
7	 newTodoValue: string
8}
9
10const initialState: State = {
11	 todos: [],
12	 newTodoValue: '',
13}
14...

This should be pretty straight forward, we just took advantage or useReducer and added another piece of state, which will handle the input value. And we just initialised it to an empty string.

Onto the reducer:

App.tsxtypescript
1const reducer = (
2  state: State,
3  action: { type: string; payload: Todo }
4): State => {
5  switch (action.type) {
6    case ADD_TODO:
7      let newTodos = [...state.todos, action.payload]
8      return { ...state, todos: newTodos, newTodoValue: '' }
9    case UPDATE_VALUE:
10      return { ...state, newTodoValue: action.payload.description }
11    default:
12      throw new Error(`Unhandled action type: ${action.type}`)
13  }
14}

Notice that we added the newTodoValue to our ADD_TODO case and set it to an empty string. This is just to clear the input after we added the todo.

The UPDATE_VALUE case is just updating the input field and the description of new todo.

One last change we need to do, is the dispatch action in our button since we want to have different IDs for our todos and more importantly, we want the description to be the value of the input.

App.tsxtypescript
1<button
2  onClick={() =>
3    dispatch({
4      type: ADD_TODO,
5      payload: {
6        id: state.todos.length + 1,
7        description: state.newTodoValue,
8      },
9    })
10  }
11>
12  Add Todo
13</button>

Phew, that was quite a few small tweaks. But now we should have fully working Todo App where we manage state with the use of useReducer hook and TypeScript.

Here is the full App component if you want to just glance through it all at once:

App.tsxtypescript
1import { useReducer } from 'react'
2
3const ADD_TODO = 'addTodo'
4const UPDATE_VALUE = 'updateValue'
5
6type Todo = {
7  id?: number
8  description: string
9}
10
11type State = {
12  todos: Todo[]
13  newTodoValue: string
14}
15
16const initialState: State = {
17  todos: [],
18  newTodoValue: '',
19}
20const reducer = (
21  state: State,
22  action: { type: string; payload: Todo }
23): State => {
24  switch (action.type) {
25    case ADD_TODO:
26      let newTodos = [...state.todos, action.payload]
27      return { ...state, todos: newTodos, newTodoValue: '' }
28    case UPDATE_VALUE:
29      return { ...state, newTodoValue: action.payload.description }
30    default:
31      throw new Error(`Unhandled action type: ${action.type}`)
32  }
33}
34
35function App() {
36  const [state, dispatch] = useReducer(reducer, initialState)
37
38  return (
39    <div>
40      <h1>Todos</h1>
41      <input
42        type="text"
43        value={state.newTodoValue}
44        onChange={(e) =>
45          dispatch({
46            type: UPDATE_VALUE,
47            payload: { description: e.target.value },
48          })
49        }
50      />
51      <button
52        onClick={() =>
53          dispatch({
54            type: ADD_TODO,
55            payload: {
56              id: state.todos.length + 1,
57              description: state.newTodoValue,
58            },
59          })
60        }
61      >
62        Add Todo
63      </button>
64      <pre>{JSON.stringify(state, null, 2)}</pre>
65    </div>
66  )
67}
68
69export default App

I hope you liked this more in depth article. If you did leave a reaction or a comment down below.

Keep learning and see you in the next one!

Join my newsletter, to receive JavaScript, TypeScript, React.js and more news, tips and other goodies right into your mail box 📥. You can unsubscribe at any time.