useReducer manages complex state logic with a reducer function.
Getting Started
What is React?
Components & Props
Components & Props
Performance & Testing
React.memo & Lazy Loading
Custom Hooks
Building Custom Hooks
Error Boundaries
Error Handling
Server Components
React Server Components
Next.js Introduction
Next.js Basics
Animations & Transitions
Framer Motion
React
Intermediate
FREE
useReducer Hook
Lesson 1 of 17
Intermediate
Interactive
Syntax
REACT
function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; } } const [state, dispatch] = useReducer(reducer, { count: 0 });
useReducer Hook
REACT
import { useReducer } from "react"; function 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: return state; } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: "increment" })}>+</button> <button onClick={() => dispatch({ type: "decrement" })}>-</button> <button onClick={() => dispatch({ type: "reset" })}>Reset</button> </div> ); }
Practice
1
Exercise
Practice this concept.
Answer
Write the code as shown above.
Quick Quiz
1
What did you learn?
This covers the basics.
Interview Questions
It is a fundamental React feature.