Table of contents
Introduction
The useReducer
hook is a built-in hook in React that allows you to manage state in a more complex way than the useState
hook. While useState
is great for managing simple state changes, useReducer
is useful for managing more complex state that involves multiple actions or events.
Syntax
Here is the basic syntax for using the useReducer
hook:
const [state, dispatch] = useReducer(reducer, initialState);
Let's break this down:
state
is the current state of the component, just like withuseState
.dispatch
is a function that allows you to update the state. When you calldispatch
, you pass in an action object that describes what change you want to make to the state.reducer
is a function that takes in the current state and an action object, and returns a new state. This function should be pure, meaning that it should always return the same output given the same input. It should not modify the original state object, but rather create a new object with the updated state.
How to use it?
Here is an example of how you might use useReducer
to manage a counter that can be incremented or decremented:
import React, { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);
}
export default Counter;
In this example, the reducer
function takes in the current state and an action object. The action object has a type
property, which we use to determine what change to make to the state. In this case, we have two possible actions: increment
and decrement
. When the user clicks the "+" button, we call dispatch({ type: "increment" })
, which tells the reducer to increment the count. Similarly, when the user clicks the "-" button, we call dispatch({ type: "decrement" })
, which tells the reducer to decrement the count.
The useReducer
hook returns an array with two elements: the current state and the dispatch function. We use object destructuring to assign these values to the state
and dispatch
variables.
In the Counter
component, we render the current count and two buttons that call the dispatch
function with the appropriate action object when clicked.
I hope this helps you understand how the useReducer
hook works in React!