Everything You Need to Create a Custom React Hook - main

In this post in our continued series on React Hooks, we learn how to use reducers building a sample todo app. Get "hooked" as we take a look at the useReducer Hook!

In the past few articles, we have become familiar with React Hooks. In our first article, we learned about State & Effect which allows us access to local state, React lifecycles and ability to produce side effects from inside a functional component. In the latest versions of React before 16.8, this was not something that could be done outside of a class component.

Try KendoReact UI Component Library for React

In our second article we learned about React's Context API and demonstrated how to use it with regular classes in a profile component. The Context API allows us to share data with child components by using a provider and consumer. The pattern was clunky and until Hooks was released, it was not achievable with functional components. In that article, we refactored with the useContext hook. This involved changing from classes to the use of functional components. We eventually removed all classes from our demo making everything easier to read with less overall code. Hooks give us the ability to migrate a lot of our code from classes to functional components especially in cases where classes were only being used to do some simple state management or tapping into lifecycles to do thing like create a side effect.

In this article, we take what we have learned and apply that knowledge to a more advanced demo using the useReducer hook. Understanding the basic useState hook can prepare us for learning about useReducer so if you have not read the first article of the series: How to Use Basic React Hooks for Reducers, it is highly encouraged and will help to reinforce the fundamentals.

Redux is the most popular way of working with unidirectional data in React and is encouraged by the React team for managing state. It has become a standard in the React community and ecosystem. In the latest releases including Hooks, React has built useReducer into React core, giving you a way to use the Redux pattern without depending on the Redux library as a dependency simply to manage UI state.

In React, Your Only Job is to Manage State

Well, not completely, but it's many React professional's opinion that one of the main things you should always consider when building React apps is "what does your state currently look like" and "what does your UI look like". This will drive how you manage state and build your application.

Don't worry, we do use separation of concerns, so the state management vs UI are kept compartmentalized. We can typically just build out UI and then focus on managing its state. This determines what we do next and we get to decide exactly what happens each time the UI is interacted with and how that might mutate the state we are managing.

A Primer on Reducers

Let's talk about the difference between a Redux state reducer and the JavaScript method Array.prototype.reduce.

The canonical array prototype example is a sum function. When we call the reducer on an array that contains only numbers, we can return a single numeric value summing up all values in the array. The reducer can be fed an initial value to start with as well. Let's briefly take a look at some code that demonstrates the reduce method from JavaScript's Array.prototype method called reduce().

const votesByDistrict = [250, 515, 333, 410];
const reducer = (accumulator, currentValue) => {
  return accumulator + currentValue;

// expected output: 1508

// and below we simply add a value to start from:

console.log(votesByDistrict.reduce(reducer, 777));
// expected output: 2285

If you have worked with Redux reducers, you probably see a similarity in the example I just created above and how Redux reducers work. You can easily see why the Redux Reducer shares a similar name.

A sum function is the simplest example, but inside that reducer, you can do any work you want iteratively between those curly braces. Think of it as a recipe that no matter what the contents of the array, this function always produces the same result considering the same input. We are talking about pure functions. This is a powerful concept, especially when used to manage state.

The Redux Reducer, similar to the Arrays reducer, returns the accumulation of something - in our case, state. Based on all previous and current actions and state modifications that have taken place in the past what we get in return is our current state.

So Redux style reducers act as a reducer of state. It receives a state and action. The state gets reduced (accumulated) based on the action type and then returned as the new state. Each reduction is referred to as a single cycle.

Just like when we cook something up in real life, for instance a Bordeaux style Bordelaise sauce , we start with many ingredients: butter, shallots, veal, pepper and of course wine. All of these ingredients are combined together in a pan and simmered or (reduced) down. If repeated and given the same steps, using the same ingredients, same amounts, same stove and same temperatures, we should yield the same result each time. A single wonderfully awesome sauce. Are you still wondering where they get the name reducer?

Let's Build a Working Example

We are going to build a todo application. To start out with, we want a todo list to have an initial todo item that simply says: "Get Started."

When we add a new todo item, the process is to first dispatch an action.

This action get's handled by a Reducer function. Our action type is ADD_TODO and our reducer function switches on a type. When the reducer function notices the type to be ADD_TODO, it acts on it by taking the old state, spreading that out and appending our new todo item to the end, we then get our new state as the result.

Another action we might create could be COMPLETE_TODO or a better name could be TOGGLE_COMPLETE. Since what we actually want to do is toggle that state on and off like a light switch. This toggling is better because if the user clicks the wrong todo and completes it on accident, they can simply just click it again to revert the state.

In this case our reducer doesn't add any new items to the list, it modifies one property of an existing todo item. Let's pick up where we left off above. If we started out with one todo that says "Get Started" and then we add a new todo: "Take a break", our new state should look like:

  id: 1, 
  name: 'Get started', 
  complete: false 
  id: 2, 
  name: 'Take a break', 
  complete: false 

Notice that each todo has several properties, one of them, an id. This is a unique key and we use it specifically to target a specific todo enabling us to change a property of that todo without affecting the rest of the todos..

The reducers job for TOGGLE_COMPLETE is to update that complete property from it's current value of false to the opposite value of true. Once this is done, any changes will be propagated down to any components that use that state, in turn causing them to update. Our list can be thought about as the listener, once we add or complete or remove a todo, the list should now reflect those new changes.

Since each completed property in our Todos start as complete: false, if we call TOGGLE_COMPLETED on the Todo with the id of 1, our state should get updated to look like:

  id: 1, 
  name: 'Get started', 
  complete: true // We changed it!
  id: 2, 
  name: 'Take a break', 
  complete: false 

We have just described (albeit in a simple example) the Redux cycle, also referred to as unidirectional data flow. Hooks makes the whole process a little easier to grok and I'm super excited about this. Think of it as a gateway to more hardcore Redux usage.

This was not easily achievable in React without a library like Redux in the past. Now we can easily implement the Redux reducer pattern in any React application without using the Redux library.

I will admit that using state in this manner should probably be reserved for working with internal state, and that this will not replace all usages of Redux. But it gives React developers a clear and concise Redux-style way of managing internal state right away without installing any dependencies.

The State We'll Manage

Traditionally in Redux, a decision on how to categorize state and where to store it was one of the biggest questions from a beginner's perspective. It's actually the first question in their Redux FAQ and here is what they say:

There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this drop-down currently open”, inside a component's internal state.

Hooks are powerful in the layer of the application where we keep track of things like “is drop-down open” and "is menu closed." We can take care of proper management of the UI data in a Redux-style manner without leaving React core.

In a machine whose sole responsibility is to constantly change and append state, the reducer is the part that is different about each operation. It's the logic that either increments a counter or manages a complex object that changes to have ramifications on the current state. Giving us access to that as well as setState from within functional components is the final piece of the puzzle - and at the same time, the first piece to a new puzzle.

Let's take a look at how we manage the very simple todo type application. It's a perfect example for demonstration purposes. Here are the rules of our todo app.

We are going to need a few moving pieces in order to contrive even a simple real world case for using useReducer. We will need to keep track of how our state is modified and updated using actions like "add," "complete" and "clear." Using a pattern familiar to Redux, we typically would associate each of these processes with a particular action type that is handled by a dispatcher:

  • A form field allowing us to enter a task
  • A dispatcher handling our form when it submits
  • An actual object that holds the our tasks
  • An actual Task Component to encompass everything
  • An actual Reducer that handles the modifying of our state

Let's start by adding and composing all of these pieces together. I don't typically go over how to setup a React project because that can be done many ways - instead I like to give my users a StackBlitz demo that they can fork and work on along side the tutorial. Once forked, this project is yours to do with as you want. You can use this information and this code however you want.

Where we start is with a brand new project and for this tutorial we will do everything inside the index.js file. Once finished, you may want to make it a point to extract each piece of logic and all components out to their own files. This is a great exercise, especially for beginners.

In our simple example, we will have the Todo component that we create be the actual root level component of our application, which would look something like the following:

import React from 'react';
import { render } from 'react-dom';
import './style.css';

const Todo = () => {
  return (
      Todo Goes Here

render(<Todo />, document.getElementById('root'));

But the code I want you to start out with is a little bit further along than that. I have added enough to get us started, including a form and input field that does not yet submit. I have also added a styled list and a chunk of Json, which we can use as a seed for generating todo items to test that our list renders out and that the shape of our data conforms to our HTML.

You will need to fork this StackBlitz Demo to follow along with the tutorial. There is a fork button on the StackBlitz demo - once you click it you can give it a new name, and this will create a clone of my starting point for you to work on.

Now that we have the project forked, we will make our first change by importing the useReducer hook from React. Update the first line in the file as follows:

import React, { useReducer } from 'react';

We need to add our call to the useReducer now. It takes state and action as arguments. We assign that to an array object which is a tuple (two values) - this is destructuring because the useReducer() matches this as its return value:

Add the following line just above the return statement in the Todo component:

const [todos, dispatch] = useReducer(todoReducer, initialState);

items will be the piece of state which is the actual list of todo items, and dispatch will be the actual reducer used to make changes to that list of items. In the return statement we create a group of divs for each item our items array.

Our application will now have errors because we have not yet created a function called todoReducer. Let's add that code right below the line that we setup our initialState assignment on.

const todoReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO': {
      return (action.name.length)
        ? [...state, {
          id: state.length ? Math.max(...state.map(todo => todo.id)) + 1 : 0,
          name: action.name,
          complete: false
        : state;
    default: {
      return state;

This may seem complex at first. All it's doing is setting up a function that takes state and action. We then switch on that action.type. At first we will only have one action, but we want to setup a default catch all as well. This default will simply return the current state.

But if it catches a real ADD_TODO we will return the current state, spread out, with our payload appended on to the end. The tricky part is assigning the new ID. What we have done here is taken the existing list of todos and returned the max id plus one, otherwise zero.

Since I have already setup an initialState, we are good to move onto the next step. We need to make sure that when typing in the input field, when we hit enter, the value we have input gets sent off to a function that will do the reducing.

So first let's replace the div with the className todo-input with the following:

<div className="todo-input">
  <form onSubmit={addTodo}>
    <input ref={inputRef} type="search" id="add-todo" placeholder="Add Todo..." />

What this does is ensure that when we hit enter, we send the form information off to a function called addTodo(). We also reference the input using the ref attribute and give that element a reference value of inputRef. Making these changes means we need to now do two more things.

1) We need to create a property called inputRef which calls the useRef hook. 2) We need to create a function called addTodo().

Let's start with creating the inputRef property. At the top of your Todo component, add the following property:

const inputRef = useRef();

We will use the ref attribute to get a reference to the input, this will allow us to access its value later. This reference will be backed by a local property in our Todo functional component, but that will just be a call to the useRef hook which allows us to access all of the ref goodness inside a functional component. With a local property named inputRef we will be able to make calls like: inputRef.value.

You will also need to import that hook just like we did with useReducer. Update the first line of the index.js file to reflect the following:

import React, { useReducer, useRef } from 'react';

Finally we need to create the addTodo() function that will use this reference and will be responsible for dispatching our action of type ADD_TODO. Just above the return add the following function:

function addTodo(event) {
    type: 'ADD_TODO',
    name: inputRef.current.value,
    complete: false
    inputRef.current.value = '';

Inside of our function we are first calling preventDefault() in order to keep the page from refreshing when we hit submit the form.

We then dispatch our ADD_TODO action using the inputRef to access the input value from the form. All todos initially get a completed value of false. Finally we set the inputRef value to nothing. This clears the input field. Good enough for a demo.

Finally, we have one more update we need to make before the ADD_TODO will work. Inside of our JSX we are still mapping over initialState. We need to change that from:

{initialState.map((todo) => (


{todos.map((todo) => (

Now we should have a working useReducer hook that is utilizing our addTodo function in order to dispatch our action to the todoReducer.

Adding Completed Todos

Let's bring in a familiar hook from our first blog post: useEffect. I just want to make sure we have a working example of that hook inside this project as well, so we will update the document.title every time that we check off a todo to display the count or number of completed todos in our list.

Just above our addTodo() function, let's add the logic for figuring out how many completed todos we have. We will then need a useEffect method to update the document.title when it changes:

const completedTodos = todos.filter(todo => todo.complete);
useEffect(() => {
  // inputRef.current.focus();
  document.title = `You have ${completedTodos.length} items completed!`;

To do this we will need to bring in that hook as well:

import React, { useReducer, useRef, useEffect } from 'react';

We are not done yet - we now need to add an event that will call the function which will dispatch our COMPLETED_TODO. Add a onClick handler to our div with the className of todo-name.

<div className="todo-name" onClick={() => toggleComplete(todo.id)}>

Next we need a function to handle this click event. It's simple and only dispatches a simple id and the action type. Add this right below our addTodo() function:

function toggleComplete(id) {
  dispatch({ type: 'TOGGLE_COMPLETE', id });

Finally we add the case to our todoReducer:

  return state.map((item) =>
    item.id === action.id
      ? { ...item, complete: !item.complete }
      : item

I have also setup a style, and we will add or remove that style based on whether the todo has a completed value of true. Just below the todos.map code, let's change the line of code that looks like this:

<div key={todo.id} alt={todo.id} className="column-item">

to this:

<div className={`column-item ${todo.complete ? 'completed' : null}`}

We don't need that alt attribute anymore, so we removed it. That should do it! Now when we click on our todos it will dispatch an action and set the completed value to true on that specific todo, and now our filter will pick up on this by way of the useEffect method which in turn updates the document.title. We will also get our className completed applied and our completed todo will become opaque to represent a completed todo.

At this point we pretty much have everything working except for the delete functionality, as well as the button that should clear all todos from the list. To round out our demo we will repeat what we have already learned in order to make these last two pieces of functionality work.

Deleting a Todo

It should be pretty trivial at this point to hook (pun intended) up a delete and clear todos button. The styling and HTML have already been taken care of, so we just need to make them work.

Let's start by adding the onClick() event for the close icon inside the todos HTML:

<div className="todo-delete" onClick={() => deleteTodo(todo.id)}>

We'll add the function that will dispatch the action - these don't have to be their own function, we could dispatch right from the onClick() or we could setup a similar switch statement to handle all of the dispatching. We can take whatever approach to this we want. I wanted to add them one by one for purposes of this demo.

Now we create a function that will handle the dispatch:

function deleteTodo(id) {
  dispatch({ type: 'DELETE_TODO', id });

And you guessed it, we now just need to add a case in our reducers switch statement to handle the reduction, this is where we actually remove a todo from the list and return the old state minus the deletion. We can do this easily because we have provided an id. In the same way we know which todo to complete by passing an id, we can also delete an item, we just need to ensure that it returns the new state. We can achieve this with the array filter prototype.

case 'DELETE_TODO': {
  return state.filter((x) => x.id !== action.id);

Clearing All Todos

For the clearing of todos, we actually don't need much. When the action gets dispatched for the CLEAR_TODOS, the only thing being passed is the actual action type, no payload, because once we get into the reducer, we are simply going to return an empty array.

Here are the three different pieces of code you will need to make that happen.

Add an onClick() to the HTML button:

onClick={() => clearTodos()}

Add a function to handle the dispatch:

function clearTodos() {
  dispatch({ type: 'CLEAR_TODOS' });

And a case in our reducer function:

case 'CLEAR_TODOS': {
  return [];

Wrap Up

We have now worked our way through building the basics of a todo application. We started with the basic structure of the todo list and how to simply repeat our a list for each todo, and eventually created all of the logic to manage the state of the list using a Redux style approach to state management. We covered adding a new todo, deleting, completing a todo and finally the ability to reset the entire todo list (the easiest part of the reducer to complete).

Look out for more articles from us that will continue our journey into Hooks and advanced Redux concepts. We have covered the basics so far and plan on showing you how to continue to take advantage of all the wonderful ways that you can utilize React Hooks and other bleeding edge features of the framework.

I hope that this has helped you understand the basics of using React Hooks for reducers. If you are new to React, we have more content here on the Telerik blog specifically around All Things React, which contains a plethora of information about React and its ecosystem. Please explore our articles and products and let me know if you have any questions or ideas for articles on subjects relating to React.

Eric Bishard
About the Author

Eric Bishard

Eric Bishard is a Developer Advocate working with KendoReact here at Progress. As a software engineer, he has experience building web based applications with a focus on components for user interfaces in frameworks like Angular and React. Feel free to connect with Eric (@httpJunkie) on Twitter!

Related Posts


Comments are disabled in preview mode.