A useReducer Guide: How to Add Interactivity With React Context
In this part we will add interactivity to our application.
We'll implement drag-and-drop using the React DnD library, and we will add state management. We won't use any external framework like Redux or Mobx. Instead, we'll throw together a poor man's version of Redux using useReducer
hook and React context API.
Before we jump into the action, I will give a little primer on using useReducer
.
Using the useReducer#
Disclaimer: The following code is separate from the Trello-clone app and is located in the examples inside the
code/01-first-app/use-reducer
folder.
useReducer
is a React hook that allows us to manage complex state-like objects with multiple fields.
The main idea is that instead of mutating the original object we always create a new instance with desired values.

The state is updated using a special function called reducer.
What is a reducer?#
A reducer is a function that calculates a new state by combining an old state with an action object.

Reducer must be a pure function. It means it shouldn't produce any side effects (I/O operations or modifying global state) and for any given input it should return the same output.
Usually a reducer looks like this:
xxxxxxxxxx
function exampleReducer(state, action) {
switch(action.type){
case "SOME_ACTION": {
return { state, updatedField: action.payload }
}
default:
return state
}
}
Depending on the passed action type
field, we return a new state value. The key point here is that we always generate a new object that represents the state.
If the passed action type did not match with any of the cases, we return the state unchanged.
How to call the useReducer
#
You can call useReducer
inside your functional components. On every state change, your component will be re-rendered.
Here's the basic syntax:
xxxxxxxxxx
const [state, dispatch] = useReducer(reducer, initialState)
useReducer
accepts a reducer and initial state. It returns the current state
paired with a dispatch
method.
dispatch
method is used to send actions to the reducer.
state
contains the current state value from the reducer.
What are actions?#
Actions are special objects that are passed to the reducer function to calculate the new state.
Actions must contain a type
field and some field for payload. The type
field is mandatory. Payload often has some arbitrary name.
This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React with TypeScript Masterclass with a single-time purchase.
