JavaScript and React course · Module 4: Context API and useReducer
Global state management
In this lesson9
As a React application grows, state management becomes an increasingly complex challenge. In small applications, local component state and props are sufficient, but as things scale, we need more advanced solutions for managing global application state.
In this module we'll look at different approaches to global state management in React, from built-in mechanisms to popular external libraries.
Challenges of global state
Before we dive into solutions, let's understand why global state management can be challenging:
- Data sharing - components in different parts of the component tree may need access to the same data
- Synchronization - changes in one place should be visible everywhere the data is used
- Predictability - state updates should be predictable and easy to trace
- Performance - unnecessary re-rendering should be minimized
- Complexity - state logic can be complicated, with many related changes
Context API + useReducer as a basic solution
As we learned in previous modules, combining Context API with useReducer provides a solid foundation for global state management:
import React, { createContext, useReducer, useContext } from 'react';
// Initial state
const initialState = {
missions: [],
activeMission: null,
user: null,
isLoading: false,
error: null
};
// Reducer
function appReducer(state, action) {
switch (action.type) {
case 'LOGIN_SUCCESS':
return { ...state, user: action.payload, error: null };
case 'LOGOUT':
return { ...state, user: null };
case 'FETCH_MISSIONS_START':
return { ...state, isLoading: true };
case 'FETCH_MISSIONS_SUCCESS':
return { ...state, missions: action.payload, isLoading: false };
case 'FETCH_MISSIONS_ERROR':
return { ...state, error: action.payload, isLoading: false };
case 'SET_ACTIVE_MISSION':
return { ...state, activeMission: action.payload };
default:
return state;
}
}
// Context
const AppStateContext = createContext();
// Provider
function AppStateProvider({ children }) {
const [state, dispatch] = useReducer(appReducer, initialState);
// We can also add helper functions
const login = async (credentials) => {
try {
dispatch({ type: 'LOGIN_START' });
// API call for login
const user = await authService.login(credentials);
dispatch({ type: 'LOGIN_SUCCESS', payload: user });
} catch (error) {
dispatch({ type: 'LOGIN_ERROR', payload: error.message });
}
};
const fetchMissions = async () => {
try {
dispatch({ type: 'FETCH_MISSIONS_START' });
const missions = await missionService.getAll();
dispatch({ type: 'FETCH_MISSIONS_SUCCESS', payload: missions });
} catch (error) {
dispatch({ type: 'FETCH_MISSIONS_ERROR', payload: error.message });
}
};
// Context value
const value = {
state,
dispatch,
login,
fetchMissions,
setActiveMission: (mission) => dispatch({ type: 'SET_ACTIVE_MISSION', payload: mission })
};
return (
<AppStateContext.Provider value={value}>
{children}
</AppStateContext.Provider>
);
}
// Hook for using context
function useAppState() {
const context = useContext(AppStateContext);
if (context === undefined) {
throw new Error('useAppState must be used within an AppStateProvider');
}
return context;
}
// Usage in application
function App() {
return (
<AppStateProvider>
<Header />
<Main />
<Footer />
</AppStateProvider>
);
}
function Header() {
const { state, dispatch } = useAppState();
return (
<header>
{state.user ? (
<>
<span>Welcome, {state.user.name}</span>
<button onClick={() => dispatch({ type: 'LOGOUT' })}>Logout</button>
</>
) : (
<LoginButton />
)}
</header>
);
}
function MissionsList() {
const { state, fetchMissions, setActiveMission } = useAppState();
useEffect(() => {
fetchMissions();
}, []);
if (state.isLoading) return <p>Loading missions...</p>;
if (state.error) return <p>Error: {state.error}</p>;
return (
<div>
<h2>Available missions</h2>
<ul>
{state.missions.map(mission => (
<li key={mission.id}>
{mission.name}
<button onClick={() => setActiveMission(mission)}>
Select
</button>
</li>
))}
</ul>
</div>
);
}This solution has several advantages:
- Uses built-in React mechanisms
- Requires no external dependencies
- Provides good structural foundations for global state
However, as the application grows, this solution may encounter limitations related to performance and code organization.
Scaling applications with multiple contexts
For larger applications, it's recommended to split global state into smaller, independent contexts by domain:
// Authentication context
const AuthContext = createContext();
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const login = async (credentials) => {
setIsLoading(true);
try {
const user = await authService.login(credentials);
setUser(user);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setIsLoading(false);
}
};
const logout = async () => {
await authService.logout();
setUser(null);
};
return (
<AuthContext.Provider value={{ user, isLoading, error, login, logout }}>
{children}
</AuthContext.Provider>
);
}
// Missions context
const MissionsContext = createContext();
function MissionsProvider({ children }) {
const [missions, setMissions] = useReducer(missionsReducer, []);
const [activeMission, setActiveMission] = useState(null);
// rest of the logic...
return (
<MissionsContext.Provider value={{ missions, activeMission, /*...*/ }}>
{children}
</MissionsContext.Provider>
);
}
// UI context
const UIContext = createContext();
function UIProvider({ children }) {
const [darkMode, setDarkMode] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(true);
// rest of the logic...
return (
<UIContext.Provider value={{ darkMode, toggleDarkMode: () => setDarkMode(!darkMode), /*...*/ }}>
{children}
</UIContext.Provider>
);
}
// Combining all providers
function AppProviders({ children }) {
return (
<AuthProvider>
<MissionsProvider>
<UIProvider>
{children}
</UIProvider>
</MissionsProvider>
</AuthProvider>
);
}Advantages of this approach:
- Better separation of concerns
- Smaller contexts = fewer unnecessary re-renders
- Easier testing of individual modules
- Components can use only the contexts they need
Performance optimization with useMemo and memo
One of the challenges when using Context API is performance - every change in the context value causes a re-render of all components that use that context. Here are some optimization techniques:
function OptimizedProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
// Memoize the context value
const contextValue = useMemo(() => {
return { state, dispatch };
}, [state, dispatch]);
return (
<AppContext.Provider value={contextValue}>
{children}
</AppContext.Provider>
);
}
// Optimizing consuming components
const MissionItem = memo(function MissionItem({ mission, onSelect }) {
return (
<li>
{mission.name}
<button onClick={() => onSelect(mission)}>Select</button>
</li>
);
});
function MissionList() {
const { missions, selectMission } = useMissions();
// Memoize callback
const handleSelect = useCallback((mission) => {
selectMission(mission);
}, [selectMission]);
return (
<ul>
{missions.map(mission => (
<MissionItem
key={mission.id}
mission={mission}
onSelect={handleSelect}
/>
))}
</ul>
);
}Introduction to Redux Toolkit
Redux is a popular state management library that offers a more structured approach to global state. Today, modern Redux means Redux Toolkit (RTK) - the official, recommended toolset that eliminates most of the boilerplate. Instead of manually writing reducers with a switch statement, we use createSlice, and instead of createStore - configureStore. Here are the basics of Redux Toolkit with React:
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useSelector, useDispatch } from 'react-redux';
// Slice = a piece of state + reducers + actions in one place
const spaceAppSlice = createSlice({
name: 'spaceApp',
initialState: {
missions: [],
user: null
},
reducers: {
// Thanks to Immer we can "mutate" state - RTK does it safely and immutably
setUser: (state, action) => {
state.user = action.payload;
},
setMissions: (state, action) => {
state.missions = action.payload;
}
}
});
// createSlice automatically generates action creators
export const { setUser, setMissions } = spaceAppSlice.actions;
// Store - configureStore adds DevTools and middleware for you
const store = configureStore({
reducer: spaceAppSlice.reducer
});
// Provider
function App() {
return (
<Provider store={store}>
<Main />
</Provider>
);
}
// Usage in components
function UserProfile() {
// Selecting part of the state
const user = useSelector(state => state.user);
const dispatch = useDispatch();
if (!user) return <p>User not logged in</p>;
return (
<div>
<h2>{user.name}</h2>
<button onClick={() => dispatch(setUser(null))}>
Logout
</button>
</div>
);
}Historical note: Classic Redux used
createStoreand manual reducers with aswitchstatement. That approach (import { createStore } from 'redux') is now deprecated - the official documentation recommends Redux Toolkit. That is why we learn the modern way from the start.
Code organization in Redux Toolkit
In larger applications, each piece of state is a separate slice. configureStore combines them automatically - you just pass a map of reducers (no manual combineReducers needed):
// /store/index.js
import { configureStore } from '@reduxjs/toolkit';
import authReducer from './auth/authSlice';
import missionsReducer from './missions/missionsSlice';
import uiReducer from './ui/uiSlice';
// configureStore combines reducers itself - no combineReducers
const store = configureStore({
reducer: {
auth: authReducer,
missions: missionsReducer,
ui: uiReducer
}
});
export default store;
// /store/missions/missionsSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
// Asynchronous operations are handled by createAsyncThunk
export const fetchMissions = createAsyncThunk(
'missions/fetchMissions',
async () => {
const missions = await api.fetchMissions();
return missions;
}
);
const missionsSlice = createSlice({
name: 'missions',
initialState: {
list: [],
active: null,
loading: false,
error: null
},
reducers: {
setActiveMission: (state, action) => {
state.active = action.payload;
}
},
// extraReducers react to the thunk states (pending/fulfilled/rejected)
extraReducers: (builder) => {
builder
.addCase(fetchMissions.pending, (state) => {
state.loading = true;
})
.addCase(fetchMissions.fulfilled, (state, action) => {
state.list = action.payload;
state.loading = false;
})
.addCase(fetchMissions.rejected, (state, action) => {
state.error = action.error.message;
state.loading = false;
});
}
});
export const { setActiveMission } = missionsSlice.actions;
export default missionsSlice.reducer;
// /store/missions/selectors.js
export const selectMissions = state => state.missions.list;
export const selectActiveMission = state => state.missions.active;
export const selectMissionsLoading = state => state.missions.loading;Modern alternatives
Many alternative state management libraries have emerged in the React ecosystem that aim to simplify the process and reduce boilerplate code. Here are some popular options:
1. Zustand
Zustand is a minimalist library that combines the simplicity of a hook with the power of a store:
import create from 'zustand';
// Creating a store
const useSpaceStore = create((set) => ({
missions: [],
activeMissionId: null,
isLoading: false,
fetchMissions: async () => {
set({ isLoading: true });
try {
const missions = await api.fetchMissions();
set({ missions, isLoading: false });
} catch (error) {
set({ error: error.message, isLoading: false });
}
},
setActiveMission: (id) => set({ activeMissionId: id })
}));
// Usage in a component
function MissionPanel() {
// Selectively fetching data from the store
const missions = useSpaceStore(state => state.missions);
const isLoading = useSpaceStore(state => state.isLoading);
const fetchMissions = useSpaceStore(state => state.fetchMissions);
useEffect(() => {
fetchMissions();
}, [fetchMissions]);
if (isLoading) return <p>Loading...</p>;
return (
<div>
<h2>Missions</h2>
<ul>
{missions.map(mission => (
<MissionItem key={mission.id} mission={mission} />
))}
</ul>
</div>
);
}2. Recoil
Recoil is a library created by Facebook that introduces the concepts of "atoms" and "selectors":
import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';
// Defining atoms (smallest units of state)
const missionsState = atom({
key: 'missionsState',
default: []
});
const missionsFilterState = atom({
key: 'missionsFilterState',
default: 'all' // 'all', 'active', 'completed'
});
// Selector (derived state)
const filteredMissionsState = selector({
key: 'filteredMissionsState',
get: ({ get }) => {
const missions = get(missionsState);
const filter = get(missionsFilterState);
switch (filter) {
case 'active':
return missions.filter(mission => mission.status === 'active');
case 'completed':
return missions.filter(mission => mission.status === 'completed');
default:
return missions;
}
}
});
// Usage in components
function MissionsFilter() {
const [filter, setFilter] = useRecoilState(missionsFilterState);
return (
<div>
<button
className={filter === 'all' ? 'active' : ''}
onClick={() => setFilter('all')}
>
All
</button>
<button
className={filter === 'active' ? 'active' : ''}
onClick={() => setFilter('active')}
>
Active
</button>
<button
className={filter === 'completed' ? 'active' : ''}
onClick={() => setFilter('completed')}
>
Completed
</button>
</div>
);
}
function MissionsList() {
// Using the filtered value
const missions = useRecoilValue(filteredMissionsState);
return (
<ul>
{missions.map(mission => (
<li key={mission.id}>{mission.name}</li>
))}
</ul>
);
}3. Jotai
Jotai, similar to Recoil, uses an atom-based approach but with a more minimalist API:
import { atom, useAtom } from 'jotai';
// Defining atoms
const userAtom = atom(null);
const missionsAtom = atom([]);
const missionFilterAtom = atom('all');
// Derived atom
const filteredMissionsAtom = atom(
(get) => {
const missions = get(missionsAtom);
const filter = get(missionFilterAtom);
switch (filter) {
case 'active':
return missions.filter(m => m.status === 'active');
case 'completed':
return missions.filter(m => m.status === 'completed');
default:
return missions;
}
}
);
// Component
function MissionDashboard() {
const [missions, setMissions] = useAtom(missionsAtom);
const [filter, setFilter] = useAtom(missionFilterAtom);
const [filteredMissions] = useAtom(filteredMissionsAtom);
// Component logic...
return (
<div>
{/* UI */}
</div>
);
}Choosing the right solution
How do you choose the best state management solution for your application? Here are some guidelines:
Application size:
- Small applications: useState + useReducer + Context API
- Medium applications: Zustand or Jotai
- Large applications: Redux (with Redux Toolkit) or Recoil
State complexity:
- Simple state: useState
- Moderately complex state: useReducer + Context API
- Complex state with relationships: Redux or Recoil
Performance requirements:
- If rendering performance is critical, consider libraries that provide granular reactivity (Recoil, Jotai)
Team experience:
- If the team knows Redux, it may be worth sticking with it
- For new projects, simpler APIs like Zustand or Jotai can speed up development
Best practices
Regardless of the chosen solution, here are some general best practices for global state management:
Minimize global state - not everything needs to be global; use local state for component-specific data
Split state by logical domains - group related data and logic together
Normalize data - avoid duplication and deep nesting
Maintain immutability - never modify state directly
Document intentions - use descriptive names for actions and selectors
Use selectors - for retrieving derived data
Keep business logic out of components - in actions, reducers, or dedicated hooks
// Example: Hook with business logic
function useMissionControl() {
const { state, dispatch } = useAppState();
const launchMission = useCallback(async (missionId) => {
// Check business conditions
if (!state.user || state.user.role !== 'commander') {
throw new Error('Only the commander can start a mission');
}
if (state.weather === 'storm') {
throw new Error('Cannot launch during a storm');
}
// Business logic
dispatch({ type: 'MISSION_LAUNCH_START', payload: missionId });
try {
await missionService.launch(missionId);
dispatch({ type: 'MISSION_LAUNCH_SUCCESS', payload: missionId });
} catch (error) {
dispatch({ type: 'MISSION_LAUNCH_FAILURE', payload: error.message });
throw error;
}
}, [state.user, state.weather, dispatch]);
return {
missions: state.missions,
activeMission: state.activeMission,
isLaunching: state.isLaunching,
launchError: state.launchError,
launchMission
};
}Summary
Global state management is a key aspect of building scalable React applications. In this module we learned about different approaches:
Context API + useReducer - React's built-in solution, good for small and medium applications
Splitting into multiple contexts - a way to organize global state by domain
Performance optimization - techniques for minimizing re-renders
Redux - a traditional library with a structured approach to state management
Modern alternatives - Zustand, Recoil, Jotai offering simpler APIs and less code
Choosing the right solution depends on the application size, state complexity, and team preferences. Regardless of the choice, following best practices will help maintain clean, predictable, and performant code.
Code for this lesson: App.jsx
import React, { useState, useEffect, useCallback, useRef } from 'react';
// Custom Hook: useLocalStorage
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
// Custom Hook: useToggle
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = useCallback(() => setValue(v => !v), []);
return [value, toggle];
}
// Custom Hook: useCounter
function useCounter(initialValue = 0, step = 1) {
const [count, setCount] = useState(initialValue);
const increment = useCallback(() => setCount(c => c + step), [step]);
const decrement = useCallback(() => setCount(c => c - step), [step]);
const reset = useCallback(() => setCount(initialValue), [initialValue]);
return { count, increment, decrement, reset };
}
// Custom Hook: useFetch
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
// Fetch simulation
setTimeout(() => {
setData({
ships: ['Explorer-1', 'Titan-7', 'Guardian-3'],
missions: 12,
crew: 45
});
setLoading(false);
}, 1500);
};
fetchData();
}, [url]);
return { data, loading, error };
}
// Custom Hook: useWindowSize
function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setSize({ width: window.innerWidth, height: window.innerHeight });
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
// Custom Hook: usePrevious
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
// Demo Component
function CustomHooksDemo() {
// useLocalStorage demo
const [name, setName] = useLocalStorage('astronaut-name', 'Cosmonaut');
// useToggle demo
const [isShieldActive, toggleShield] = useToggle(false);
// useCounter demo
const { count: fuel, increment: addFuel, decrement: useFuel, reset: resetFuel } = useCounter(50, 10);
// useFetch demo
const { data, loading, error } = useFetch('/api/station');
// useWindowSize demo
const { width, height } = useWindowSize();
// usePrevious demo
const previousFuel = usePrevious(fuel);
return (
<div style={{
fontFamily: 'Arial, sans-serif',
padding: '20px',
maxWidth: '800px',
margin: '0 auto',
backgroundColor: '#0a0a1a',
minHeight: '100vh',
color: 'white'
}}>
<h1 style={{ textAlign: 'center', color: '#00d4ff' }}>Custom Hooks</h1>
{/* useLocalStorage */}
<section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
<h2 style={{ color: '#4caf50' }}>useLocalStorage</h2>
<p>Astronaut name (saved in localStorage):</p>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
style={{
padding: '10px',
width: '100%',
boxSizing: 'border-box',
borderRadius: '8px',
border: '1px solid #333',
backgroundColor: '#252545',
color: 'white'
}}
/>
<p style={{ color: '#888', fontSize: '14px' }}>Refresh the page - the value will be preserved!</p>
</section>
{/* useToggle */}
<section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
<h2 style={{ color: '#ff9800' }}>useToggle</h2>
<div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
<button
onClick={toggleShield}
style={{
padding: '12px 24px',
backgroundColor: isShieldActive ? '#4caf50' : '#f44336',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
{isShieldActive ? 'Shields ACTIVE' : 'Shields OFFLINE'}
</button>
</div>
</section>
{/* useCounter */}
<section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
<h2 style={{ color: '#2196f3' }}>useCounter</h2>
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: '48px', fontWeight: 'bold', color: fuel < 30 ? '#f44336' : '#4caf50' }}>
{fuel}%
</div>
<p>Fuel (previously: {previousFuel ?? '-'}%)</p>
<div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
<button onClick={useFuel} style={{ padding: '10px 20px', backgroundColor: '#f44336', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>-10</button>
<button onClick={resetFuel} style={{ padding: '10px 20px', backgroundColor: '#666', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>Reset</button>
<button onClick={addFuel} style={{ padding: '10px 20px', backgroundColor: '#4caf50', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>+10</button>
</div>
</div>
</section>
{/* useFetch */}
<section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
<h2 style={{ color: '#9c27b0' }}>useFetch</h2>
{loading ? (
<p>Loading station data... ⏳</p>
) : (
<div>
<p>Ships: {data?.ships?.join(', ')}</p>
<p>Active missions: {data?.missions}</p>
<p>Crew members: {data?.crew}</p>
</div>
)}
</section>
{/* useWindowSize */}
<section style={{ padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
<h2 style={{ color: '#e91e63' }}>useWindowSize</h2>
<p>Window size: {width} x {height} px</p>
<p style={{ color: '#888', fontSize: '14px' }}>Resize the browser window!</p>
</section>
</div>
);
}
export default CustomHooksDemo;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. When is the default context value passed to createContext used?
2. What happens when a component is between two Providers of the same context?
Hands-on tasks in the game
- Vertical ordering
Arrange what happens when the value in a Provider changes:
- Code editor
Implement a space inventory system
- Vertical ordering
Arrange the steps for creating a galactic fleet management system:
- Code editor
Implement a fleet command center