Since React introduced hooks, I worked with them on several projects and they are just great.
Removing all class-based components makes the code feel much more “real” JavaScript. And functional components can finally manage state.
Check out my React hooks introduction first, if you’re new to them.
One hook I sometimes use is useReducer
.
import React, { useReducer } from 'react'
This hook is used to manage state. Sort of like useState
, except more complex.
This is the key difference between useState
and useReducer
: with useReducer
, state is altered by passing messages rather than calling the updater function.
If you know how Redux works, that’s basically the same. A reducer is a pure function that calculates the next state based on the previous state and the action that has been dispatched.
(currentState, action) => newState
What does “pure function” mean? A pure function takes an input and returns an output without changing the input or anything else. This means that a reducer returns a completely new state that substitutes the previous one.
A reducer should:
- never mutate its arguments
- never generate side-effects (no API calls changing anything)
- never call non-pure functions, functions that change their output based on factors other than their input (e.g.
Date.now()
orMath.random()
)
There is no reinforcement, but you should stick to the rules. And this has a nice benefit: reducers are much simpler to test, because they have no side effects.
This allows to centralize the state management, allowing components to modify it by sending messages, and also allows you to use (and alter) a more complex state in your components.
Let’s do an example, with a counter component.
useReducer
accepts as arguments a reducer function, and an initial state value. In this case our state is an integer, which starts from 0:
const Counter = () => {
const [state, dispatch] = useReducer(reducer, 0)
}
The reducer is a function that takes, as explained above, the current state and an action, which can be a value of any type you want. In this case it’s a string:
const reducer = (state, action) => {
switch (action) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
throw new Error()
}
}
We also make the component output some JSX to make this simple app work:
const Counter = () => {
const [count, dispatch] = useReducer(reducer, 0)
return (
<>
Counter: {count}
<button onClick={() => dispatch('INCREMENT')}>+</button>
<button onClick={() => dispatch('DECREMENT')}>-</button>
</>
)
}
Here is the full example on Codepen:
See the Pen React useReducer hook by Flavio Copes (@flaviocopes) on CodePen.
Now, imagine this state can be an object with many many properties, and different actions only change one property at a time. That’s a great use case for this hook.
Download my free React Handbook
More react tutorials:
- A React simple app example: fetch GitHub users information via API
- Build a simple counter with React
- VS Code setup for React development
- How to pass props to a child component via React Router
- Create an app with Electron and React
- Tutorial: create a Spreadsheet using React
- The roadmap to learn React
- Learn how to use Redux
- Getting started with JSX
- Styled Components
- Introduction to Redux Saga
- Introduction to React Router
- Introduction to React
- React Components
- The Virtual DOM
- React Events
- The React State
- React Props
- The React Fragment
- The React Context API
- React PropTypes
- React concepts: declarative
- React: How to show a different component on click
- How to loop inside React JSX
- Props vs State in React
- Should you use jQuery or React?
- How much JavaScript you need to know to use React?
- Introduction to Gatsby
- How to reference a DOM element in React
- Unidirectional Data Flow in React
- React Higher Order Components
- React Lifecycle Events
- React Concept: Immutability
- React Concept: Purity
- Introduction to React Hooks
- Introduction to create-react-app
- React Concept: Composition
- React: Presentational vs Container Components
- Code Splitting in React
- Server Side Rendering with React
- How to install React
- CSS in React
- Using SASS in React
- Handling Forms in React
- React StrictMode
- React Portals
- React Render Props
- Testing React components
- How to pass a parameter to event handlers in React
- How to handle errors in React
- How to return multiple elements in JSX
- Conditional rendering in React
- React, how to transfer props to child components
- How to get the value of an input element in React
- How to use the useState React hook
- How to use the useCallback React hook
- How to use the useEffect React hook
- How to use the useMemo React hook
- How to use the useRef React hook
- How to use the useContext React hook
- How to use the useReducer React hook
- How to connect your React app to a backend on the same origin
- The Reach Router Tutorial
- How to use the React Developer Tools
- How to learn React
- How to debug a React application
- How to render HTML in React
- How to fix the `dangerouslySetInnerHTML` did not match error in React
- How I fixed an issue with a React login form state and Browser autofill
- How to configure HTTPS in a React app on localhost
- How to fix the "cannot update a component while rendering a different component" error in React
- Can I use React hooks inside a conditional?
- Using useState with an object: how to update
- How to move around blocks of code with React and Tailwind