Course
useReducer
React Mastery Guide
Unlock the full potential of React with our comprehensive guide. From basics to advanced techniques, this course covers everything you need to build dynamic, high-performance web applications. Perfect for developers at any level, start mastering React today!
useReducer
Previously, we used
setState
to directly modify values. But what if we need to execute some logics before updating the value?
This is where useReducer comes in:
import React, { Reducer, useEffect, useReducer, useState } from 'react';import './App.css';
interface Data { result: number;}
interface Action { type: 'add' | 'minus', num: number}function reducer(state: Data, action: Action) {
switch (action.type) { case 'add': return { result: state.result + action.num } case 'minus': return { result: state.result - action.num } } return state;}
function App() { const [res, dispatch] = useReducer<Reducer<Data, Action>>(reducer, { result: 0 });
return ( <> <h1>React Hooks</h1> <div className="card"> <p>count is {res.result}</p> <div className="button-container"> <button onClick={() => dispatch({ type: 'add', num: 2 })}>Add</button> <button onClick={() => dispatch({ type: 'minus', num: 1 })}>Minus</button> </div> <p> Edit <code>src/App.tsx</code> and save to test Hooks </p> </div> <p className="read-the-docs"> Click on the Vite and React logos to learn more </p> </> );}
export default App;
Let's try it out!
For
useReducer
, you pass type parameters like Reducer<type of data, type of action>.The first argument is the reducer function, and the second argument is the initial state.
When you click "add," it triggers the "add" action, and when you click "minus," it triggers the "minus" action.
Of course, you can also use setState directly:
import { useState } from 'react';import './App.css';
function App() { const [res, setRes] = useState({ result: 0});
return ( <> <h1>React Hooks</h1> <div className="card"> <p>count is {res.result}</p> <div className="button-container"> <button onClick={() => setRes({ result: res.result + 2 })}>Add</button> <button onClick={() => setRes({ result: res.result - 1 })}>Minus</button> </div> <p> Edit <code>src/App.tsx</code> and save to test Hooks </p> </div> <p className="read-the-docs"> Click on the Vite and React logos to learn more </p> </> );}
export default App;
Some might argue that
useState
is much simpler than useReducer
.Indeed, for simple examples,
useReducer
might be unnecessary.
But what if the logic is more complex?
With
useState
, you would need to repeat the logic in every place where the state is updated, while useReducer
allows you to encapsulate this logic within the reducer and trigger it via actions.When the logic for modifying the state is complex, use useReducer.