Context with useReducer in React
Course: React JS Training
Topic: Combining Context API with useReducer for Shared State Management
Learning Objectives: Understand how Context and useReducer work together, manage complex state, avoid prop drilling, dispatch actions from nested components, and organize shared state in a reusable React application.
Course Links: JustAcademy React JS Training | Register for React JS Course Demo
1. Introduction to Context with useReducer
React provides several Hooks for managing application state. The useState Hook is useful for simple state, while useReducer is helpful when state updates involve multiple actions or more complex logic. The Context API allows data to be shared with deeply nested components without passing props through every intermediate component.
When an application grows, many components may need to read or update the same state. Combining Context with useReducer provides a structured solution: the reducer manages state transitions, while Context makes the state and dispatch function available to descendant components.
For example, a task management application may contain components for adding tasks, displaying tasks, editing tasks, and deleting tasks. Instead of passing the task list and event handlers through several component levels, a shared provider can make them available to the components that need them.
Key Concepts
- Context API: Makes values available to descendant components without manually forwarding props at every level.
- useReducer: Manages state through a reducer function that calculates the next state from the current state and an action.
- Reducer: A function that receives the current state and an action and returns the next state.
- Action: An object describing an event or requested state change.
- Dispatch: A function used to send an action to the reducer.
- Provider: Supplies a context value to components inside its subtree.
2. What Is useReducer?
useReducer is a React Hook that manages state using a reducer function. Instead of updating state directly in several event handlers, components dispatch actions that describe what happened. The reducer determines how the state should change.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
Parameters
| Parameter |
Description |
| reducer |
A pure function that receives the current state and an action and returns the next state. |
| initialState |
The initial value of the state. |
| init (optional) |
An optional initializer function used to calculate the initial state. |
Return Values
state represents the current state.
dispatch sends an action to the reducer and requests a state update.
Basic Example
import { useReducer } from 'react';
function counterReducer(state, action) {
switch (action.type) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
case "reset":
return 0;
default:
return state;
}
}
function Counter() {
const [count, dispatch] = useReducer(counterReducer, 0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => dispatch({ type: "increment" })}>
Increase
</button>
<button onClick={() => dispatch({ type: "decrement" })}>
Decrease
</button>
<button onClick={() => dispatch({ type: "reset" })}>
Reset
</button>
</div>
);
}
export default Counter;
Explanation: The reducer handles three actions. Each button dispatches an action, and React uses the reducer's returned value as the next state.
3. What Is the Context API?
The Context API allows a component to provide information to components deeper in its tree without requiring each intermediate component to receive and forward that information through props.
Common Use Cases
- Current user or account information.
- Application theme settings.
- Language preferences.
- Shared task or cart state.
- Feature-level application state used by multiple nested components.
Creating a Context
import { createContext } from 'react';
export const AppContext = createContext(null);
The value passed to createContext is the default value used when a matching provider is not available above a consumer. In this example, the default value is null.
Reading a Context
import { useContext } from 'react';
import { AppContext } from './AppContext';
function UserInfo() {
const value = useContext(AppContext);
return <p>Context value: {String(value)}</p>;
}
The useContext Hook reads the value from the nearest matching provider above the component.
4. Why Combine Context with useReducer?
Using only useReducer can centralize state update logic, but components outside the reducer-owning component may still need state and callback props. Using only Context can share values, but complex update logic may become difficult to organize if many components update the state in different ways.
Combining the two gives each tool a clear responsibility:
- useReducer: Defines how application state changes.
- Context: Shares the current state and dispatch function with descendant components.
- useContext: Allows components to read the shared values.
- dispatch: Allows components to request changes by sending actions.
How the Pattern Works
App
|
useReducer(reducer)
/ \
state dispatch
\ /
Context
|
Shared Provider
|
-------------------------
| | |
AddTask TaskList TaskActions
| | |
Dispatch Read Dispatch
In this structure, the provider makes state and dispatch available to components below it. Components can read state or dispatch actions without passing these values through every intermediate component.
5. Step-by-Step: Combining Context and useReducer
Step 1: Create the Contexts
It is often helpful to create separate contexts for state and dispatch. Components that only need to dispatch actions can consume the dispatch context without subscribing to the state context.
import { createContext } from 'react';
export const TasksContext = createContext(null);
export const TasksDispatchContext = createContext(null);
Step 2: Create the Reducer
The reducer contains the rules for changing the task list. Each action type represents a specific operation.
function tasksReducer(tasks, action) {
switch (action.type) {
case "added":
return [
...tasks,
{
id: action.id,
text: action.text,
done: false
}
];
case "changed":
return tasks.map(task =>
task.id === action.task.id
? action.task
: task
);
case "deleted":
return tasks.filter(task => task.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
The reducer returns a new array for each update rather than mutating the existing array. This immutable approach helps React identify state changes reliably.
Step 3: Create the Initial State
const initialTasks = [
{ id: 1, text: "Learn React", done: false },
{ id: 2, text: "Practice useReducer", done: false }
];
The initial state contains two sample tasks. Each task has an ID, a text description, and a completion status.
Step 4: Create the Provider Component
import { useReducer } from 'react';
import {
TasksContext,
TasksDispatchContext
} from './TasksContext';
function tasksReducer(tasks, action) {
switch (action.type) {
case "added":
return [
...tasks,
{
id: action.id,
text: action.text,
done: false
}
];
case "changed":
return tasks.map(task =>
task.id === action.task.id ? action.task : task
);
case "deleted":
return tasks.filter(task => task.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
const initialTasks = [
{ id: 1, text: "Learn React", done: false },
{ id: 2, text: "Practice useReducer", done: false }
];
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(
tasksReducer,
initialTasks
);
return (
<TasksContext value={tasks}>
<TasksDispatchContext value={dispatch}>
{children}
</TasksDispatchContext>
</TasksContext>
);
}
React version note: The example uses React 19's direct context-provider syntax. For React 18 and earlier, use <TasksContext.Provider value={tasks}> and <TasksDispatchContext.Provider value={dispatch}> instead.
The provider component owns the reducer and supplies its two return values through Context. The children prop represents the components rendered inside the provider.
Step 5: Create Custom Hooks for Access
Custom Hooks make it easier to read shared state and dispatch actions without repeating the same useContext logic throughout the application.
import { useContext } from 'react';
import {
TasksContext,
TasksDispatchContext
} from './TasksContext';
export function useTasks() {
const context = useContext(TasksContext);
if (context === null) {
throw new Error("useTasks must be used inside TasksProvider");
}
return context;
}
export function useTasksDispatch() {
const context = useContext(TasksDispatchContext);
if (context === null) {
throw new Error(
"useTasksDispatch must be used inside TasksProvider"
);
}
return context;
}
These Hooks provide a convenient interface for components. They also produce a clear error if a component is rendered outside the required provider.
6. Using the Provider in the App Component
Wrap the part of the component tree that needs access to the shared task state in the provider.
import { TasksProvider } from './TasksProvider';
import AddTask from './AddTask';
import TaskList from './TaskList';
export default function App() {
return (
<TasksProvider>
<main>
<h1>My Task Manager</h1>
<AddTask />
<TaskList />
</main>
</TasksProvider>
);
}
Both AddTask and TaskList can now access the task state or dispatch function using the custom Hooks. App does not need to pass task data and event handlers through every component.
7. Reading Shared State in a Component
A component that displays the task list can call useTasks() to read the current task state.
import { useTasks } from './TasksHooks';
export default function TaskList() {
const tasks = useTasks();
return (
<section>
<h2>Tasks</h2>
{tasks.length === 0 ? (
<p>No tasks available.</p>
) : (
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.text} - {task.done ? "Completed" : "Pending"}
</li>
))}
</ul>
)}
</section>
);
}
TaskList does not receive the tasks as a prop. It reads them directly from Context and displays the current data.
8. Updating Shared State with dispatch
Components can use the dispatch context to request state updates. The reducer decides how each action changes the shared state.
Example: Adding a Task
import { useState } from 'react';
import { useTasksDispatch } from './TasksHooks';
let nextId = 3;
export default function AddTask() {
const [text, setText] = useState("");
const dispatch = useTasksDispatch();
function handleSubmit(event) {
event.preventDefault();
const trimmedText = text.trim();
if (!trimmedText) {
return;
}
dispatch({
type: "added",
id: nextId++,
text: trimmedText
});
setText("");
}
return (
<form onSubmit={handleSubmit}>
<input
value={text}
onChange={event => setText(event.target.value)}
placeholder="Enter a task"
/>
<button type="submit">Add Task</button>
</form>
);
}
The input's temporary text is local state, while the shared task collection is managed by the reducer. On submission, AddTask dispatches an action that asks the reducer to add a new task.
Note: This example uses a module-level ID counter for simplicity. In production applications, use a reliable ID-generation strategy appropriate to the application, and avoid generating IDs or performing other side effects inside the reducer.
9. Editing and Deleting Tasks
Components that update or delete a task can dispatch the corresponding actions without receiving handler props from their parents.
Complete Task Item Example
import { useTasksDispatch } from './TasksHooks';
export default function TaskItem({ task }) {
const dispatch = useTasksDispatch();
function handleToggle() {
dispatch({
type: "changed",
task: {
...task,
done: !task.done
}
});
}
function handleDelete() {
dispatch({
type: "deleted",
id: task.id
});
}
return (
<li>
<label>
<input
type="checkbox"
checked={task.done}
onChange={handleToggle}
/>
<span>{task.text}</span>
</label>
<button onClick={handleDelete}>Delete</button>
</li>
);
}
TaskItem receives the individual task through a prop from TaskList, but it gets the dispatch function directly from Context. This demonstrates that Context and props can work together; using Context does not mean eliminating all props.
10. Understanding the Complete Data Flow
When a user performs an action, the application follows a predictable sequence:
- The user clicks a button or submits a form.
- The component dispatches an action containing a type and any required data.
- React calls the reducer with the current state and the action.
- The reducer calculates and returns the next state.
- React stores the new state and renders the affected UI.
- The provider supplies the updated state through Context.
- Components that consume the changed context value can render the latest information.
Example Flow
User clicks "Add Task"
|
v
AddTask dispatches:
{ type: "added", id: 3, text: "Study React" }
|
v
tasksReducer(currentTasks, action)
|
v
Returns a new tasks array
|
v
useReducer stores next state
|
v
TasksContext provides updated tasks
|
v
TaskList renders the new task
11. Context with useReducer vs useState
| Feature |
useState + Context |
useReducer + Context |
| State updates |
Updates are often written in setter calls. |
Updates are described by actions and handled by a reducer. |
| Best suited for |
Relatively simple shared state. |
Multiple related actions and more complex state transitions. |
| Update logic |
May be distributed among event handlers. |
Centralized in the reducer. |
| Organization |
Often shorter for simple use cases. |
Provides a consistent structure as update logic grows. |
| Context's role |
Shares state and setter functions. |
Shares state and the dispatch function. |
| Complexity |
Simple to understand for small features. |
Requires defining action types and reducer cases. |
Neither pattern is universally better. Use useState for straightforward state updates and consider useReducer when multiple actions or related values make update logic more complex.
12. Advantages of Context with useReducer
- Reduces prop drilling: Components can access shared state without forwarding it through every intermediate level.
- Centralizes update logic: State transitions are defined in a reducer function.
- Improves consistency: Components read from the same shared state source.
- Organizes actions: Action types describe operations such as adding, editing, and deleting.
- Supports reusable components: Descendants can access shared data without requiring every ancestor to know about it.
- Improves maintainability: State updates are easier to locate and test when reducer logic is clearly separated.
- Supports feature-level state: A provider can be placed around the specific part of the application that needs the shared state.
13. Limitations and Challenges
- Additional setup: Contexts, providers, reducers, and custom Hooks introduce more code.
- Context updates: Components consuming a context can re-render when its provided value changes.
- Hidden dependencies: A component's dependence on Context may be less obvious than an explicit prop.
- Action design: Poorly named or inconsistent actions can make reducer logic difficult to understand.
- Overuse: Small pieces of local state usually do not need a shared provider.
- Testing considerations: Components that use custom context Hooks generally need the appropriate provider in tests.
Use this pattern for state that genuinely needs to be shared. Keep unrelated state local and organize providers around meaningful features.
14. Best Practices
- Keep reducers pure: do not perform network requests, mutate external variables, or generate random IDs inside the reducer.
- Return new arrays and objects instead of mutating existing state.
- Use clear action names such as
added, changed, and deleted.
- Include only the information needed by the reducer in each action.
- Keep the provider close to the part of the application that needs the shared state when possible.
- Use separate contexts for state and dispatch when that separation makes dependencies clearer.
- Create custom Hooks to centralize Context access and provider validation.
- Do not store values that can easily be derived from the existing state.
- Keep form input state local when it does not need to be shared.
- Use Context and useReducer as a feature-level state solution rather than automatically making every state value global.
- Remember that dispatch schedules a state update; reading the current state immediately after dispatch still returns the value from the current render.
- Call Hooks at the top level of components or custom Hooks, never inside loops or conditional branches.
15. Common Mistakes and Solutions
| Mistake |
Problem |
Solution |
| Mutating state inside the reducer |
Existing state may be changed unexpectedly, and React may not detect the intended update. |
Return a new array or object. |
| Forgetting the provider |
Consumers may receive the default context value instead of the expected state or dispatch. |
Wrap consumers with the required provider. |
| Using the wrong action type |
The reducer may not handle the requested operation. |
Use consistent action names and handle each expected action. |
| Performing side effects in the reducer |
Reducers become unpredictable and difficult to test. |
Keep side effects in event handlers, Effects, or an appropriate external layer. |
| Using Context for all state |
Local state becomes unnecessarily global. |
Keep state close to the components that use it. |
| Passing a new object unnecessarily |
New provider values can trigger context updates even when the logical data is unchanged. |
Keep values stable when appropriate and optimize based on measured needs. |
| Creating IDs in the reducer |
The reducer is no longer pure. |
Generate IDs before dispatching the action. |
| Expecting dispatch to return the new state |
dispatch does not return the next state. |
Use the state value from the next render. |
16. Mini Project: Shared Task Manager
Project Objective: Build a task manager where users can add, complete, and delete tasks. Manage the task list using useReducer and share it through Context.
Required Features
- Display the task list.
- Add a new task.
- Mark a task as completed or pending.
- Delete a task.
- Show the total number of tasks.
- Share state without passing the task list and dispatch function through every intermediate component.
Project Structure
src/
├── App.jsx
├── TasksContext.jsx
├── TasksProvider.jsx
├── TasksHooks.jsx
├── AddTask.jsx
├── TaskList.jsx
└── TaskItem.jsx
Implementation Plan
- Create contexts for tasks and dispatch.
- Define the initial task list.
- Write a reducer with added, changed, and deleted actions.
- Create a provider using useReducer.
- Build custom Hooks for reading state and dispatching actions.
- Create AddTask to dispatch the added action.
- Create TaskList to read and display tasks.
- Create TaskItem to dispatch changed and deleted actions.
- Wrap the application in TasksProvider.
- Test all task operations and verify that the UI stays synchronized.
Expected Learning Outcome: You will understand how reducer-based state updates and Context work together to create a shared state system without unnecessary prop drilling.
17. Interview Questions and Answers
Q1. What is Context with useReducer in React?
Answer: It is a pattern that combines useReducer for managing state transitions with Context for making the current state and dispatch function available to descendant components.
Q2. Why combine Context and useReducer?
Answer: The reducer centralizes state update logic, while Context makes shared state and its dispatch function accessible without passing them through multiple component levels.
Q3. What does useReducer return?
Answer: It returns an array containing the current state and a dispatch function.
Q4. What is a reducer function?
Answer: A reducer is a pure function that receives the current state and an action and returns the next state.
Q5. What is dispatch?
Answer: Dispatch sends an action to the reducer. React then uses the reducer's result as the next state.
Q6. What is the purpose of separate state and dispatch contexts?
Answer: They allow components to depend on the state, the dispatch function, or both. This can make dependencies clearer and can avoid state-context subscriptions for components that only need dispatch.
Q7. Can useReducer be used without Context?
Answer: Yes. useReducer can manage state inside a single component or a component that passes its state and handlers to children through props.
Q8. Can Context be used with useState?
Answer: Yes. Context can provide state and setter functions created with useState. useReducer is another option when the update logic becomes more complex.
Q9. Why should a reducer be pure?
Answer: A pure reducer produces the same result for the same state and action without modifying external data or performing side effects. This makes state transitions predictable and testable.
Q10. What happens if a component uses a context outside its provider?
Answer: It receives the context's default value. If that value is null, a custom Hook can throw a helpful error explaining that the provider is missing.
Q11. Does Context prevent all unnecessary re-renders?
Answer: No. Components consuming a context may re-render when its provided value changes. Context solves value distribution, not every performance problem.
Q12. When should you use Context with useReducer?
Answer: Use it when multiple descendant components need to read or update the same state and that state has several related actions or complex update rules.
18. Practice Exercises
- Create a counter using useReducer and share its state through Context.
- Build a task list with add, edit, complete, and delete actions.
- Create a shopping cart where product components dispatch add-to-cart actions.
- Build a theme manager using Context and useReducer.
- Create a user settings panel with actions to update multiple related preferences.
- Write unit tests for a reducer to verify that each action returns the expected state.
- Refactor a component tree that passes state and callbacks through multiple levels into a provider-based solution.
Self-Assessment Checklist
- Can you explain useReducer and Context separately?
- Can you create a reducer with multiple action types?
- Can you create a context and a provider component?
- Can you share state and dispatch through separate contexts?
- Can you create custom Hooks for accessing Context?
- Can you update arrays and objects immutably?
- Can you explain when this pattern is more useful than useState alone?
- Can you identify when local state or ordinary props are sufficient?
19. Official Learning Resources
20. Conclusion
Context with useReducer is a useful React pattern for managing complex shared state. useReducer organizes state transitions into a reducer function, while Context distributes the state and dispatch function to components that need them. Together, they help reduce prop drilling, keep update logic centralized, and make larger component trees easier to maintain.
Use this approach when multiple descendant components need shared state and several related actions. For simpler interactions, local state and ordinary props may remain the clearest solution.
Explore the course: JustAcademy React JS Training | Register for React JS Course Demo