What is useReducer hook in react
Posted 4 years ago by Ryan Dhungel
Category: React Hooks
Viewed 4875 times
Estimated read time: 10 seconds
In this tutorial you will learn how to use useReducer hook in react.
useReducer
is an alternative touseState
- It takes a
reducer
as an argument - Example of
reducer
using arrow function(state, action) => newState
reducer
function takes astate
andaction
. Actions will make some changes to the state.- Once actions do their job, reducer then returns a new state
- A reducer is a function that determines changes to an application's state paired with dispatch method
- It works similar to how redux works
useReducer
is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one
Here is an example of using useReducer in react app
import React, { useReducer } from "react";
// initial state
const initialState = { count: 0 };
// reducer function
const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
case "RESET":
return { count: 0 };
default:
throw new Error();
}
};
const Counter = () => {
// useReducer first argument is reducer function. second argument is initialState
// you can destructure state value and dispatch function to access/modify state
// dispatch function takes type/string and payload/data
// IMPORTANT! pass the initial state as a second argument
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
<button onClick={() => dispatch({ type: "RESET", payload: 0 })}>
RESET
</button>
</>
);
};
export default Counter;