Nearby lessons
23 of 44⚛️ ReactJS – useReducer Hook
📌 What is useReducer?
What is useReducer? Why do we use it?
useReducer is a React Hook used for state management.
It is an alternative to useState(), and is usually preferred for handling complex state logic.
While useState is good for simple state updates, useReducer is better when your state logic involves multiple conditions or actions.
📌 What is useReducer?
- It is a Hook for managing complex state logic
- Alternative to useState
- Takes a reducer function and an initial state
- Returns [state, dispatch]
⚙️ Syntax of useReducer
The useReducer hook takes two arguments:
- reducer → A function that handles state transitions
- initialState → The starting value of the state
It returns an array with:
state→ Current statedispatch→ Function to trigger actions
const [state, dispatch] = useReducer(reducer, initialState);
⚡ Execution Flow of useReducer
- Initial Setup: The
useReducerhook is called with areducerfunction and aninitialState. It returns:state→ the current state value.dispatch→ a function used to send actions.
- Rendering: The component renders using the current
state. - Dispatch Action: When an event occurs (e.g., button click, form submit),
dispatch(action)is called with a specific action object or value. - Reducer Execution: The
reducerfunction is executed with two arguments:state→ the current state.action→ the dispatched action.
- Re-render: React updates the component with the new
state, causing a re-render with the latest data.
🧮 Example – Counter with useReducer
Below example demonstrates a simple counter app using useReducer.
- Initial Setup: The
useReducerhook is called with areducerfunction and aninitialState. It returns an array with two values:count→ the current state value.dispatch→ a function to send actions to the reducer.
- Rendering: The component displays the initial
countvalue (0). - Dispatch Action: When a button is clicked, it calls
dispatch("Increment")ordispatch("Decrement"). - Reducer Execution: The
reducerfunction runs with the current state and the action:- If action =
"Increment"→ returnsstate + 1. - If action =
"Decrement"→ returnsstate - 1.
- If action =
- Re-render: The new state is set as
count, and React re-renders the component with the updated value.
React Playground
import React from 'react'; import './App.css'; import Counter from './Counter'; function App() { return ( <> <h1>Learning useReducer</h1> <Counter/> </> ); } export default App;
🔑 Key Points
- Reducer function decides how the state changes
- Dispatch is used to send an action
- Each action type should be handled in the reducer
- Good for managing complex state transitions
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4
Keep Going!React - useCallback Hook