React HooksMedium
What is useReducer and when should you use it over useState?
useReducer is an alternative to useState that is deeply inspired by Redux. It is designed for managing complex state objects or state logic that involves multiple sub-values or interconnected updates.
The Architecture:
- State: The data object representing your component's state.
- Action: An object describing what happened (e.g.,
{ type: 'ADD_ITEM', payload: item }). - Reducer: A pure function
(state, action) => newStatethat determines how the state changes based on the action. - Dispatch: The function you call from your UI to send an action to the reducer.
When to choose useReducer:
- When the next state depends heavily on the previous state.
- When state transitions are complex and involve multiple variables (e.g., fetching data: handling
loading,data, anderrorstates simultaneously). - When you want to decouple state logic from the component rendering to make it easier to test.
Code example
tsx
1import React, { useReducer } from 'react';23// 1. Define initial state4const initialState = {5 data: [],6 loading: false,7 error: null8};910// 2. Define the reducer function (Pure, predictable logic)11function dataReducer(state, action) {12 switch (action.type) {13 case 'FETCH_START':14 return { ...state, loading: true, error: null };15 case 'FETCH_SUCCESS':16 return { ...state, loading: false, data: action.payload };17 case 'FETCH_ERROR':18 return { ...state, loading: false, error: action.payload };19 case 'DELETE_ITEM':20 return {21 ...state,22 data: state.data.filter(item => item.id !== action.payload)23 };24 default:25 return state;26 }27}2829export default function DataDashboard() {30 // 3. Initialize the hook31 const [state, dispatch] = useReducer(dataReducer, initialState);3233 const handleFetch = async () => {34 dispatch({ type: 'FETCH_START' });35 try {36 // Simulated API Call37 const res = await new Promise(r => setTimeout(() => r([{ id: 1, name: 'Item A' }]), 1000));38 dispatch({ type: 'FETCH_SUCCESS', payload: res });39 } catch (err) {40 dispatch({ type: 'FETCH_ERROR', payload: 'Failed to load' });41 }42 };4344 return (45 <div className="p-6 border rounded-xl">46 <button47 onClick={handleFetch}48 disabled={state.loading}49 className="bg-purple-600 text-white px-4 py-2 rounded"50 >51 {state.loading ? 'Loading...' : 'Fetch Data'}52 </button>5354 {state.error && <p className="text-red-500 mt-4">{state.error}</p>}5556 <ul className="mt-4 space-y-2">57 {state.data.map(item => (58 <li key={item.id} className="flex justify-between p-3 bg-gray-50 rounded">59 {item.name}60 <button onClick={() => dispatch({ type: 'DELETE_ITEM', payload: item.id })}>61 ❌62 </button>63 </li>64 ))}65 </ul>66 </div>67 );68}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.