Hello! Let's dive into our next lesson on advanced state management.
In our previous session, we mastered typing useReducer actions with discriminated unions, creating a robust, self-contained state machine. However, that state machine was confined to a single component. The "prop drilling" problem, which we discussed when introducing useContext, remains if we need to share that state or dispatch actions from distant components.
Today, we'll connect these two powerful concepts. Our goal is to combine useReducer and useContext to create a scalable state management solution. This pattern is the foundation of many robust React applications and serves as a powerful alternative to external state management libraries like Redux for a wide range of use cases.
The Core Idea: Separating Logic from Distribution
The synergy between useReducer and useContext comes from a clean separation of concerns:
useReducerhandles the "how": It provides a centralized place—the reducer function—to manage all state transition logic. This makes your state updates predictable and easy to debug.useContexthandles the "where": It provides a mechanism to broadcast the state and the dispatch function down the component tree, making them available wherever they are needed without passing props through intermediate components.
Think of it like this: useReducer is the application's central processing unit (CPU), executing all the state logic. useContext is the system bus, making the results of that processing (the state) and the ability to trigger new processing (the dispatch function) available to all other parts of the system.
This architecture creates a clear data flow that is highly scalable and maintainable.

Building Our State Management System
We're going to build a global state management system step-by-step. The article "Don't Reach for Redux Just Yet" by Samuel Owolabi provides an excellent, practical walkthrough of this exact pattern. We will follow its structure, and I'll guide you through the key concepts.
Don't Reach for Redux Just Yet: Mastering State with React ...
This article is our primary guide for this lesson. It details how to build a type-safe state management system for a fintech dashboard using useReducer, useContext, and TypeScript. It's a comprehensive and practical resource.
Please read the article from the beginning up to and including 'Step 5: Using Your New Context!'. We will walk through each step together. Pay close attention to the file structure and how the types, reducer, and context provider are separated and then brought together.
Let's break down the process outlined in the article.
Step 1: Define Your Types and Reducer
First, as detailed in Step 1 (reducerTypes.tsx) and Step 2 (reducer.tsx) of the article, you define the shape of your state and the possible actions using a discriminated union, and then implement the reducer function. This should be very familiar from our last lesson. This approach keeps your state logic pure and separate from your components.
A key takeaway for building a scalable system is organizing your code. The article suggests a contexts directory with separate files for:
reducerTypes.tsx: All TypeScript types.reducer.tsx: The reducer function and initial state.appContext.tsx: The context provider and consumer hook.
This separation of concerns is a fundamental software engineering principle that pays dividends as an application grows.
Step 2: Create the Context Provider Component
This is where we combine the two hooks. As shown in Step 3 (appContext.tsx) of the article, the process is:
-
Create the Context: A context is created with
React.createContext(). The crucial part here is typing it correctly. The value it will hold is an object containing both thestateand thedispatchfunction. The article defines aContextValueTypefor this.// Type for the context value that will be provided export type ContextValueType = { state: ContextStateType; dispatch: Dispatch<ContextActionTypes>; }; const AppContext = createContext<ContextValueType | undefined>(undefined);Initializing with
undefinedis a common pattern that we'll handle with a custom hook. -
Create the Provider Component: This is a regular React component (
AppProvider) that will wrap the parts of your application that need access to the state.- Inside this component, you call
useReducer, which returns the currentstateand thedispatchfunction. - You then render the
AppContext.Provider, passing an object{ state, dispatch }as itsvalueprop. - All
childrenof this provider will now be able to access this value.
export const AppProvider: React.FC<AppProviderProps> = ({ children }) => { const [state, dispatch] = useReducer(reducer, initialState); const value: ContextValueType = { state, dispatch }; return ( <AppContext.Provider value={value}> {children} </AppContext.Provider> ); }; - Inside this component, you call
Step 3: Create a Custom Hook for Consumption
While you could export AppContext and use useContext(AppContext) in your components, this is not ideal. It's verbose, and you'd have to handle the potential undefined value in every component.
A much cleaner pattern, also shown in Step 3, is to create a custom hook (useAppContext) that encapsulates the useContext call and adds a runtime check.
Why use a Custom Hook for React Context API instead of useContext (+ TypeScript)
Why go to the trouble of creating a custom hook? This video from ByteGrad explains the benefits clearly. It shows how a custom hook abstracts away implementation details, making your components cleaner and preventing common errors.
Watch from 03:04 to 06:08. The video highlights two key problems with direct useContext usage: having to import the context variable everywhere, and needing to perform a null/undefined check in every consumer component. The custom hook solves both.
The implementation of the custom hook is concise and powerful:
export const useAppContext = (): ContextValueType => {
const context = useContext(AppContext);
if (context === undefined) {
// This error is a great developer experience safeguard.
throw new Error('useAppContext must be used within an AppProvider');
}
return context;
};
Now, consumer components just call useAppContext() and are guaranteed to receive the context value, or else get a clear error message during development if the provider is missing.
Step 4: Wrap and Use
Finally, as shown in Step 4 (layout.tsx) and Step 5 (usage-examples.tsx), you:
- Wrap your application's component tree with your
<AppProvider />. - In any child component, call your custom hook to get access to the global state and dispatch function.
// In any component inside AppProvider...
const { state, dispatch } = useAppContext();
const toggleTheme = () => {
dispatch({
type: 'SET_THEME',
payload: state.theme === 'light' ? 'dark' : 'light'
});
};
return (
<div>
<p>Current Theme: {state.theme}</p>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
The component is now completely decoupled from where the state lives or how it's managed. It simply consumes the state and dispatches actions.
A Complete Video Walkthrough
The steps above give you the blueprint. To see it all come together in a live-coding format, the following video by Dave Gray provides a great, detailed demonstration. He builds a similar system from scratch for a counter component.
Context API React + Typescript | useContext & useReducer Examples
This video walks through creating a global state management system for a counter, complete with TypeScript types. It covers all the steps we've just discussed: creating the types and reducer, defining the context, building the provider, and creating custom hooks to consume the state.
I recommend watching from 01:38 to 24:28. You don't need to code along right now, but focus on how the pieces connect. Pay attention to his pattern of creating separate custom hooks (useCounter and useCounterText) to provide more granular access to the context. This is a nice pattern for components that only need a slice of the state.
Advanced Topic: Performance Optimization
There is one important subtlety with the pattern we've just built. When we provide { state, dispatch } as a single object, any component that calls useAppContext() will re-render whenever any part of the state object changes.
This is true even for components that only use the dispatch function and don't actually read any state. This can lead to unnecessary re-renders.
For a truly scalable solution, we can optimize this by splitting our context into two:
- A
StateContextto provide thestate. - A
DispatchContextto provide thedispatchfunction.
Since the dispatch function from useReducer is stable and never changes between renders, components that only consume DispatchContext will not re-render when the state changes.
Managing Global State in React with Context and ...
The article 'Managing Global State in React with Context and useReducer' from Konabos briefly illustrates this advanced optimization technique.
Focus on the code image in 'Step 2: Create Separate Contexts for State and Dispatch'. It shows the creation of TodoStateContext and TodoActionContext (which they use for dispatch). This visualizes the core idea of splitting the context for performance.
A component that only needs to add a todo, for example, could then be written like this:
// Consuming only the dispatch context
const { addTodo } = useTodoActions(); // A custom hook for dispatch actions
return <button onClick={() => addTodo('New Task')}>Add Todo</button>;
This component would not re-render when other parts of the todo list state (like toggling an existing todo) change. This is a powerful optimization for large applications.
Test your understanding!
Imagine you have a UserContext that provides { user, login, logout } to the entire application. The user object contains user details, while login and logout are dispatch functions.
You have a Header component that displays the user's name if they are logged in. You also have a SettingsPage component that only contains a "Logout" button.
Based on the performance optimization pattern, how would you design your context and hooks to prevent the SettingsPage from re-rendering every time the user's details (e.g., their name) are updated?
Show answer
You would create two separate contexts and two corresponding custom hooks:
UserStateContext: Provides theuserobject.UserDispatchContext: Provides theloginandlogoutfunctions.useUserState()hook: ConsumesUserStateContext.useUserDispatch()hook: ConsumesUserDispatchContext.
- The
Headercomponent would use theuseUserState()hook to get theuserobject and display the name. It would re-render when user data changes. - The
SettingsPagecomponent would use only theuseUserDispatch()hook to get thelogoutfunction. Because thelogoutfunction is stable, this component would not re-render when theuserobject in theUserStateContextchanges.
This setup effectively isolates components that only perform actions from state updates they don't care about.
Conclusion
You have now learned one of the most powerful and scalable state management patterns available directly within React. By combining the predictable state transitions of useReducer with the prop-drilling solution of useContext, you can manage complex global state without adding any external libraries.
Key Takeaways:
useReducerhandles the state logic, whileuseContexthandles state distribution.- The common pattern involves creating a
Providercomponent that usesuseReducerand passes the resultingstateanddispatchfunction down via the context'svalueprop. - Creating a custom consumer hook (e.g.,
useAppContext) is a best practice that improves developer experience by encapsulating theuseContextcall and providing a runtime check for the provider's existence. - For optimal performance in large applications, you can split your context into a
StateContextand aDispatchContextto prevent components that only dispatch actions from re-rendering unnecessarily.
Preview of the Next Lesson:
We've spent a lot of time managing data and state within React's virtual world. However, sometimes we need to break out of that declarative model and interact directly with the "real" DOM. In our next lesson, we will introduce the useRef hook to access DOM elements directly for imperative actions, such as managing focus, triggering animations, or integrating with third-party DOM libraries.