JavaScript and React course ยท Module 4: Context API and useReducer
useReducer - advanced state management
In this lesson8
In a spaceship's command center, a simple panel with one button is not enough. When onboard systems become increasingly complex - shields, engines, navigation systems, alarms - we need a more organized way to manage state. The useReducer hook is like the central onboard computer that receives orders (actions) and updates the state of all systems based on strictly defined rules.
What is useReducer?
useReducer is an alternative to useState, designed to handle more complex state logic. Instead of directly setting a new value, you send an action (command), and a special function called a reducer decides how the state should change.
Basic syntax
const [state, dispatch] = useReducer(reducer, initialState);Where:
state- the current state (ship system data)dispatch- the function for sending actions (issuing commands)reducer- a function that returns a new state based on the current state and actioninitialState- the initial state value
Space analogy: Think of dispatch as the control panel where you press buttons (actions). The onboard computer (reducer) receives the command and calculates the new state based on the ship's current state. You never modify systems manually - always through the computer!
The reducer function
A reducer is a pure function that takes two arguments: the current state and an action. Based on these, it returns a new state object. We most commonly use a switch statement to handle different action types:
function spaceshipReducer(state, action) {
switch (action.type) {
case 'ACTIVATE_SHIELDS':
return { ...state, shields: 100, status: 'defended' };
case 'FIRE_ENGINES':
return { ...state, speed: state.speed + action.payload, fuel: state.fuel - 10 };
case 'EMERGENCY_STOP':
return { ...state, speed: 0, status: 'stopped' };
default:
return state;
}
}Key reducer rules:
- Always return a new state object (don't mutate the previous one)
- Handle
default- return the unchanged state for unknown actions - The reducer should be a pure function - no side effects, no randomness
Dispatch and action objects
An action is a plain JavaScript object with a type field describing the kind of operation. You can optionally add a payload field with additional data:
// Simple action - type only
dispatch({ type: 'ACTIVATE_SHIELDS' });
// Action with data (payload)
dispatch({ type: 'FIRE_ENGINES', payload: 50 });
// Action with complex payload
dispatch({
type: 'ADD_CREW_MEMBER',
payload: { name: 'Captain Nova', role: 'pilot' }
});Practical example - ship control panel
Let's see how useReducer performs in managing complex control panel state:
import { useReducer } from 'react';
const initialShipState = {
fuel: 100,
shields: 0,
speed: 0,
status: 'docked',
log: []
};
function shipReducer(state, action) {
switch (action.type) {
case 'LAUNCH':
if (state.fuel < 20) return state;
return {
...state,
status: 'flying',
fuel: state.fuel - 20,
speed: 50,
log: [...state.log, 'Ship launched']
};
case 'BOOST':
if (state.status !== 'flying' || state.fuel < 10) return state;
return {
...state,
speed: state.speed + action.payload,
fuel: state.fuel - 10,
log: [...state.log, `Accelerated by ${action.payload} km/s`]
};
case 'TOGGLE_SHIELDS':
return {
...state,
shields: state.shields > 0 ? 0 : 100,
log: [...state.log, state.shields > 0 ? 'Shields deactivated' : 'Shields activated']
};
case 'DOCK':
return {
...state,
status: 'docked',
speed: 0,
log: [...state.log, 'Ship docked']
};
case 'REFUEL':
return {
...state,
fuel: 100,
log: [...state.log, 'Fuel replenished']
};
default:
return state;
}
}
function ShipControlPanel() {
const [ship, dispatch] = useReducer(shipReducer, initialShipState);
return (
<div className="control-panel">
<h2>Control panel</h2>
<p>Status: {ship.status}</p>
<p>Fuel: {ship.fuel}%</p>
<p>Shields: {ship.shields}%</p>
<p>Speed: {ship.speed} km/s</p>
<button onClick={() => dispatch({ type: 'LAUNCH' })}
disabled={ship.status === 'flying'}>
Launch
</button>
<button onClick={() => dispatch({ type: 'BOOST', payload: 25 })}
disabled={ship.status !== 'flying'}>
Boost (+25)
</button>
<button onClick={() => dispatch({ type: 'TOGGLE_SHIELDS' })}>
{ship.shields > 0 ? 'Deactivate shields' : 'Activate shields'}
</button>
<button onClick={() => dispatch({ type: 'DOCK' })}
disabled={ship.status === 'docked'}>
Dock
</button>
<button onClick={() => dispatch({ type: 'REFUEL' })}
disabled={ship.status === 'flying'}>
Refuel
</button>
<div className="ship-log">
<h3>Ship log:</h3>
<ul>
{ship.log.map((entry, i) => (
<li key={i}>{entry}</li>
))}
</ul>
</div>
</div>
);
}Notice how the reducer centralizes all the state update logic. The component doesn't need to know exactly how the state changes - it just needs to send the appropriate action. This is a huge advantage for complex interfaces.
When to use useReducer instead of useState?
Both hooks serve to manage state, but they have different use cases:
Choose useState when:
- The state is simple (number, string, boolean)
- The update logic is simple (direct assignment)
- You have several independent values
Choose useReducer when:
- The state is a complex object with many fields
- Updating one field requires changing other fields
- You have many related actions (e.g., start, stop, reset, boost)
- The update logic contains conditions (e.g., don't launch without fuel)
- You want to easily test state logic separately from the component
// useState - sufficient for simple cases
const [isOpen, setIsOpen] = useState(false);
const [count, setCount] = useState(0);
// useReducer - better for complex state
const [shipState, dispatch] = useReducer(shipReducer, {
fuel: 100,
shields: 0,
speed: 0,
status: 'docked',
crew: [],
alerts: [],
systems: { engine: 'online', navigation: 'online', weapons: 'offline' }
});The switch-case pattern in reducers
The switch statement is the standard pattern in reducers. Here are some best practices:
// Define constants for action types - avoid typos
const ACTIONS = {
LAUNCH: 'LAUNCH',
DOCK: 'DOCK',
BOOST: 'BOOST',
TAKE_DAMAGE: 'TAKE_DAMAGE',
REPAIR: 'REPAIR'
};
function shipReducer(state, action) {
switch (action.type) {
case ACTIONS.LAUNCH:
return { ...state, status: 'flying', speed: 50 };
case ACTIONS.DOCK:
return { ...state, status: 'docked', speed: 0 };
case ACTIONS.BOOST:
return {
...state,
speed: Math.min(state.speed + action.payload, 300)
};
case ACTIONS.TAKE_DAMAGE: {
const newShields = Math.max(0, state.shields - action.payload);
return {
...state,
shields: newShields,
status: newShields === 0 ? 'critical' : state.status
};
}
case ACTIONS.REPAIR:
return { ...state, shields: 100, status: 'docked' };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
// Usage with constants
dispatch({ type: ACTIONS.BOOST, payload: 50 });
dispatch({ type: ACTIONS.TAKE_DAMAGE, payload: 30 });Notice that in TAKE_DAMAGE we used a block {} inside the case - this allows declaring local variables (newShields) without conflicts with other cases. Additionally, instead of default: return state, we throw an error - this helps catch typos in action names during development.
Action creators
For convenience and readability, you can create functions that generate action objects:
// Action creators
const launch = () => ({ type: 'LAUNCH' });
const boost = (amount) => ({ type: 'BOOST', payload: amount });
const takeDamage = (amount) => ({ type: 'TAKE_DAMAGE', payload: amount });
const addCrewMember = (name, role) => ({
type: 'ADD_CREW_MEMBER',
payload: { name, role }
});
// Usage - more readable than manually creating objects
dispatch(launch());
dispatch(boost(50));
dispatch(takeDamage(25));
dispatch(addCrewMember('Nova', 'pilot'));Action creators reduce the risk of typos and centralize action creation logic in one place.
Summary
useReducer is a powerful tool for managing complex state in React:
- Syntax:
const [state, dispatch] = useReducer(reducer, initialState) - Reducer: a pure function
(state, action) => newStatewith the switch-case pattern - Dispatch: sending actions
dispatch({ type: 'ACTION', payload: data }) - When to use: complex state, related updates, business logic in state
- Best practices: constants for action types, action creators,
{}blocks in case, throwing errors in default
Just as the central onboard computer of a spaceship coordinates the work of all systems based on commands from the captain's bridge, useReducer centralizes state logic, making it predictable and easy to manage.
Code for this lesson: App.jsx
import React, { useState, useMemo, useCallback, memo } from 'react';
// Component without optimization (for comparison)
function UnoptimizedItem({ name, onSelect }) {
console.log('Rendering UnoptimizedItem:', name);
return (
<div style={{
padding: '10px',
backgroundColor: '#ffebee',
marginBottom: '5px',
borderRadius: '4px'
}}>
{name}
<button onClick={() => onSelect(name)} style={{ marginLeft: '10px' }}>Select</button>
</div>
);
}
// Component optimized with React.memo
const OptimizedItem = memo(function OptimizedItem({ name, onSelect }) {
console.log('Rendering OptimizedItem:', name);
return (
<div style={{
padding: '10px',
backgroundColor: '#e8f5e9',
marginBottom: '5px',
borderRadius: '4px'
}}>
{name}
<button onClick={() => onSelect(name)} style={{ marginLeft: '10px' }}>Select</button>
</div>
);
});
// Heavy computations (simulation)
function expensiveCalculation(numbers) {
console.log('Running expensive calculation...');
let result = 0;
for (let i = 0; i < 100000000; i++) {
result += numbers.reduce((a, b) => a + b, 0);
}
return numbers.reduce((a, b) => a + b, 0);
}
function PerformanceDemo() {
const [count, setCount] = useState(0);
const [numbers] = useState([1, 2, 3, 4, 5]);
const [selectedItem, setSelectedItem] = useState('');
const [darkMode, setDarkMode] = useState(false);
const items = ['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'];
// Without useMemo - computation on every render
// const sum = expensiveCalculation(numbers);
// With useMemo - computation only when 'numbers' changes
const sum = useMemo(() => {
console.log('Computing sum with useMemo...');
return numbers.reduce((a, b) => a + b, 0);
}, [numbers]);
// Without useCallback - new function on every render
// const handleSelect = (name) => setSelectedItem(name);
// With useCallback - stable reference
const handleSelect = useCallback((name) => {
setSelectedItem(name);
}, []);
// Styles optimized with useMemo
const containerStyle = useMemo(() => ({
fontFamily: 'Arial, sans-serif',
padding: '20px',
maxWidth: '900px',
margin: '0 auto',
backgroundColor: darkMode ? '#1a1a2e' : '#f5f5f5',
color: darkMode ? 'white' : '#333',
minHeight: '100vh',
transition: 'all 0.3s ease'
}), [darkMode]);
return (
<div style={containerStyle}>
<h1 style={{ textAlign: 'center', color: '#667eea' }}>Performance Optimization</h1>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '30px',
padding: '15px',
backgroundColor: darkMode ? '#252545' : '#fff',
borderRadius: '12px'
}}>
<div>
<button
onClick={() => setCount(c => c + 1)}
style={{
padding: '10px 20px',
backgroundColor: '#667eea',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
marginRight: '10px'
}}
>
Count: {count}
</button>
<button
onClick={() => setDarkMode(!darkMode)}
style={{
padding: '10px 20px',
backgroundColor: darkMode ? '#fff' : '#333',
color: darkMode ? '#333' : 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
{darkMode ? 'Light' : 'Dark'}
</button>
</div>
<div>
Selected: <strong>{selectedItem || 'None'}</strong>
</div>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
{/* useMemo Demo */}
<section style={{
padding: '20px',
backgroundColor: darkMode ? '#252545' : '#fff',
borderRadius: '12px'
}}>
<h2 style={{ color: '#4caf50' }}>useMemo</h2>
<p>Array sum: <strong>{sum}</strong></p>
<p style={{ fontSize: '14px', color: '#888' }}>
Computations performed only when the 'numbers' array changes.
Click "Count" - the sum won't be recalculated!
</p>
<pre style={{
backgroundColor: darkMode ? '#1a1a2e' : '#f5f5f5',
padding: '10px',
borderRadius: '8px',
fontSize: '12px',
overflow: 'auto'
}}>
{`const sum = useMemo(() => {
return numbers.reduce((a, b) => a + b, 0);
}, [numbers]);`}
</pre>
</section>
{/* React.memo Demo */}
<section style={{
padding: '20px',
backgroundColor: darkMode ? '#252545' : '#fff',
borderRadius: '12px'
}}>
<h2 style={{ color: '#2196f3' }}>React.memo + useCallback</h2>
<p style={{ fontSize: '14px', color: '#888', marginBottom: '15px' }}>
Check the console! Optimized elements don't re-render when count changes.
</p>
<h4>Without optimization:</h4>
{items.slice(0, 2).map(item => (
<UnoptimizedItem
key={item}
name={item}
onSelect={(name) => setSelectedItem(name)}
/>
))}
<h4 style={{ marginTop: '20px' }}>Z React.memo + useCallback:</h4>
{items.slice(0, 2).map(item => (
<OptimizedItem
key={item}
name={item}
onSelect={handleSelect}
/>
))}
</section>
</div>
<section style={{
marginTop: '20px',
padding: '20px',
backgroundColor: darkMode ? '#252545' : '#fff',
borderRadius: '12px'
}}>
<h2 style={{ color: '#ff9800' }}>When to optimize?</h2>
<ul style={{ lineHeight: '1.8' }}>
<li><strong>useMemo:</strong> Expensive computations, creating objects/arrays</li>
<li><strong>useCallback:</strong> Callbacks passed to optimized children</li>
<li><strong>React.memo:</strong> Components that don't change often</li>
<li><strong>Note:</strong> Don't optimize prematurely! Measure first.</li>
</ul>
</section>
</div>
);
}
export default PerformanceDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the useReducer hook return?
Hands-on tasks in the game
- Click in order
Build a correct useReducer declaration:
- Code editor
Create a research station system
- Horizontal ordering
Arrange the correct structure of an action object in useReducer:
- Vertical ordering
Arrange the components of a space application architecture from most general to most specific:
- Code editor
Create a galactic data bank