JavaScript and React course ยท Module 12: React and TypeScript
Typing Context API and useReducer
In this lesson5
The color theme has to reach every panel from the bridge, and the mission list every cabin. Passing props through five levels of components is exhausting, and without types it's easy to dispatch an action with a typo that the reducer silently ignores. The Context API is a communication system between distant spaceship modules - it lets you pass data without threading it through every intermediate component. TypeScript ensures this data always has the correct shape.
Typing the Context API
We build a typed context in four steps. First an interface describing what the context provides, then the context itself with createContext. We create the context with the value undefined and the type ThemeContextType | undefined - I'll explain why in a moment.
import React, { createContext, useContext, useState } from 'react';
// 1. Define the context type
interface ThemeContextType {
theme: "dark" | "light";
toggleTheme: () => void;
}
// 2. Create context with a default value
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);The third step is a custom hook that reads the context and checks whether the component is inside a Provider at all. The fourth is the Provider, the component that holds the state and shares it with its descendants:
// 3. Custom hook to use context (with validation)
function useTheme(): ThemeContextType {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error("useTheme must be used inside ThemeProvider");
}
return context;
}
// 4. Provider component
function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<"dark" | "light">("dark");
const toggleTheme = () => {
setTheme(prev => prev === "dark" ? "light" : "dark");
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}After the if statement, TypeScript narrows context to ThemeContextType, so the hook returns a type without undefined. New in React 19: you can render the context itself as the Provider by writing <ThemeContext value={...}>. <ThemeContext.Provider> still works and you'll see it in most code, but the React team has announced it will be deprecated in a future version.
Why Use undefined as the Default Value?
The default value in createContext only reaches components that have no Provider above them. Compare the two approaches:
// Pattern: createContext<T | undefined>(undefined)
// + custom hook with validation
// ADVANTAGES:
// - Runtime error if component is not inside a Provider
// - Type in component is always ThemeContextType (not undefined)
// - Safer than providing an "empty" default object
// ALTERNATIVE (less safe):
const ThemeContext = createContext<ThemeContextType>({
theme: "dark",
toggleTheme: () => {} // empty function - silent bug
});In the alternative, a component outside the Provider gets an empty function - the theme button simply does nothing and nobody finds out why. The undefined pattern turns silent failures into a loud message. This is the pattern I recommend.
Typing useReducer
useReducer is ideal for managing complex state. A reducer is a pure function that receives the current state and an action and returns the new state. TypeScript makes every action and state change safe. We start with the state type and the type of a single mission:
// 1. Define the state type
interface MissionState {
missions: Mission[];
selectedMission: Mission | null;
loading: boolean;
error: string | null;
}
interface Mission {
id: string;
name: string;
status: "planned" | "active" | "completed";
}We describe actions as a discriminated union from the previous lesson. The discriminator is the type field, and each variant has its own payload type. Mission["status"] takes the type of the status field from the interface, so we don't repeat the list of statuses:
// 2. Define action types - discriminated union!
type MissionAction =
| { type: "SET_MISSIONS"; payload: Mission[] }
| { type: "SELECT_MISSION"; payload: string }
| { type: "ADD_MISSION"; payload: Mission }
| { type: "UPDATE_STATUS"; payload: { id: string; status: Mission["status"] } }
| { type: "SET_LOADING"; payload: boolean }
| { type: "SET_ERROR"; payload: string | null };Now the reducer. In every case, TypeScript knows the exact type of action.payload: in "ADD_MISSION" it's Mission, in "SET_LOADING" it's boolean.
// 3. Reducer with full typing
function missionReducer(state: MissionState, action: MissionAction): MissionState {
switch (action.type) {
case "SET_MISSIONS":
return { ...state, missions: action.payload, loading: false };
case "SELECT_MISSION":
return {
...state,
selectedMission: state.missions.find(m => m.id === action.payload) || null
};
case "ADD_MISSION":
return { ...state, missions: [...state.missions, action.payload] };
case "UPDATE_STATUS":
return {
...state,
missions: state.missions.map(m =>
m.id === action.payload.id
? { ...m, status: action.payload.status }
: m
)
};
case "SET_LOADING":
return { ...state, loading: action.payload };
case "SET_ERROR":
return { ...state, error: action.payload, loading: false };
default:
return state;
}
}The reducer never modifies the old state - it always returns a new object via ...state. The action { type: "ADD_MISION" } with a typo won't compile, because it matches no variant.
Combining Context + useReducer
Now we connect the reducer to a context, so every fleet component can read the state and dispatch actions. The React.Dispatch<MissionAction> type describes a dispatch function that accepts only valid actions:
// Initial state
const initialState: MissionState = {
missions: [],
selectedMission: null,
loading: false,
error: null
};
// Context type
interface MissionContextType {
state: MissionState;
dispatch: React.Dispatch<MissionAction>;
}
const MissionContext = createContext<MissionContextType | undefined>(undefined);The hook and the Provider repeat the theme pattern. Notice that useReducer gets no generics - it infers the types from missionReducer and initialState. The hook's type signature changed in React 19 and the old useReducer<State, Action>(...) form now reports an error, so rely on inference.
// Custom hook
function useMissions(): MissionContextType {
const context = useContext(MissionContext);
if (!context) {
throw new Error("useMissions must be used inside MissionProvider");
}
return context;
}
// Provider
function MissionProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(missionReducer, initialState);
return (
<MissionContext.Provider value={{ state, dispatch }}>
{children}
</MissionContext.Provider>
);
}Using It in Components
The mission list component gets the state and dispatch with one hook call. The editor suggests the allowed type values, and after you pick "SELECT_MISSION" it requires a payload of type string:
function MissionList() {
const { state, dispatch } = useMissions();
if (state.loading) return <p>Loading missions...</p>;
if (state.error) return <p>Error: {state.error}</p>;
return (
<div>
{state.missions.map(mission => (
<div key={mission.id} onClick={() =>
dispatch({ type: "SELECT_MISSION", payload: mission.id })
}>
<h3>{mission.name}</h3>
<span>{mission.status}</span>
</div>
))}
</div>
);
}MissionList knows nothing about where the state lives - it only knows the hook. In the final project the same setup will handle the theme of the whole dashboard.
Code for this lesson: App.tsx
import React, { createContext, useContext, useReducer, useState } from 'react';
// ===== TYPES =====
interface CrewMember {
id: string;
name: string;
role: string;
status: "active" | "resting" | "mission";
}
// Application state
interface AppState {
crew: CrewMember[];
theme: "dark" | "light";
notifications: string[];
}
// Discriminated union of actions
type AppAction =
| { type: "ADD_CREW"; payload: CrewMember }
| { type: "REMOVE_CREW"; payload: string }
| { type: "UPDATE_STATUS"; payload: { id: string; status: CrewMember["status"] } }
| { type: "TOGGLE_THEME" }
| { type: "ADD_NOTIFICATION"; payload: string }
| { type: "CLEAR_NOTIFICATIONS" };
// ===== REDUCER =====
function appReducer(state: AppState, action: AppAction): AppState {
switch (action.type) {
case "ADD_CREW":
return {
...state,
crew: [...state.crew, action.payload],
notifications: [...state.notifications, "Added: " + action.payload.name]
};
case "REMOVE_CREW":
return {
...state,
crew: state.crew.filter(c => c.id !== action.payload),
notifications: [...state.notifications, "Removed a crew member"]
};
case "UPDATE_STATUS":
return {
...state,
crew: state.crew.map(c =>
c.id === action.payload.id ? { ...c, status: action.payload.status } : c
)
};
case "TOGGLE_THEME":
return { ...state, theme: state.theme === "dark" ? "light" : "dark" };
case "ADD_NOTIFICATION":
return { ...state, notifications: [...state.notifications, action.payload] };
case "CLEAR_NOTIFICATIONS":
return { ...state, notifications: [] };
default:
return state;
}
}
// ===== CONTEXT =====
interface AppContextType {
state: AppState;
dispatch: React.Dispatch<AppAction>;
}
const AppContext = createContext<AppContextType | undefined>(undefined);
function useApp(): AppContextType {
const context = useContext(AppContext);
if (!context) throw new Error("useApp requires AppProvider");
return context;
}
// ===== PROVIDER =====
const initialState: AppState = {
crew: [
{ id: "1", name: "Nova", role: "Captain", status: "active" },
{ id: "2", name: "Ra", role: "Navigator", status: "active" },
{ id: "3", name: "Astro", role: "Engineer", status: "resting" },
],
theme: "dark",
notifications: []
};
function AppProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
<div className={"app " + state.theme}>{children}</div>
</AppContext.Provider>
);
}
// ===== COMPONENTS =====
function Header() {
const { state, dispatch } = useApp();
return (
<header className="header">
<h1>Command Center</h1>
<button onClick={() => dispatch({ type: "TOGGLE_THEME" })}>
{state.theme === "dark" ? "Light" : "Dark"} theme
</button>
</header>
);
}
function CrewList() {
const { state, dispatch } = useApp();
const statusColors = { active: "#22c55e", resting: "#f59e0b", mission: "#818cf8" };
const statuses: CrewMember["status"][] = ["active", "resting", "mission"];
return (
<div className="section">
<h2>Crew ({state.crew.length})</h2>
{state.crew.map(member => (
<div key={member.id} className="crew-card">
<div>
<strong>{member.name}</strong> - {member.role}
</div>
<div className="crew-actions">
<select
value={member.status}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>
dispatch({
type: "UPDATE_STATUS",
payload: { id: member.id, status: e.target.value as CrewMember["status"] }
})
}
>
{statuses.map(s => <option key={s} value={s}>{s}</option>)}
</select>
<span style={{ color: statusColors[member.status] }}>{member.status}</span>
<button className="small-btn danger"
onClick={() => dispatch({ type: "REMOVE_CREW", payload: member.id })}>
X
</button>
</div>
</div>
))}
</div>
);
}
function AddCrewForm() {
const { dispatch } = useApp();
const [name, setName] = useState("");
const [role, setRole] = useState("");
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name || !role) return;
dispatch({
type: "ADD_CREW",
payload: { id: Date.now().toString(), name, role, status: "active" }
});
setName("");
setRole("");
};
return (
<form onSubmit={handleSubmit} className="add-form">
<input value={name} onChange={e => setName(e.target.value)} placeholder="Name" />
<input value={role} onChange={e => setRole(e.target.value)} placeholder="Role" />
<button type="submit">Add</button>
</form>
);
}
function Notifications() {
const { state, dispatch } = useApp();
if (state.notifications.length === 0) return null;
return (
<div className="section notifications">
<h2>Notifications ({state.notifications.length})</h2>
{state.notifications.map((n, i) => <p key={i} className="notif">{n}</p>)}
<button onClick={() => dispatch({ type: "CLEAR_NOTIFICATIONS" })}>Clear</button>
</div>
);
}
function App() {
return (
<AppProvider>
<Header />
<AddCrewForm />
<CrewList />
<Notifications />
</AppProvider>
);
}
export default App;Remember: context is the fleet's communication network and the action type is its cipher - a message with the wrong cipher never leaves the bridge.
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. Why is it recommended to use createContext<Type | undefined>(undefined) instead of providing a default object?
2. Why is it best to define action types in useReducer as a discriminated union?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for creating a typed Context with useReducer in the correct order:
- Code editor
Full typing of Context API with useReducer
- Click in order
Arrange the code of a custom hook with context validation:
- Horizontal ordering
Arrange the correct type for dispatch in the context interface:
- Vertical ordering
Arrange TypeScript concepts in React from simplest to most complex:
- Horizontal ordering
Arrange the syntax for creating a typed React context:
- Click in order
Arrange the signature of a typed reducer function:
- Vertical ordering
Arrange the data flow in Context + useReducer architecture in the correct order:
- Horizontal ordering
Arrange a correct dispatch call with a typed action:
- Click in order
Arrange the elements of a typed Provider component:
- Vertical ordering
Arrange the benefits of TypeScript in React from the most basic to the most advanced:
- Code editor
Comprehensive exercise combining all TypeScript concepts in React
Tasks after this lesson
- QuestionDefault Value of createContext
- QuestionuseReducer Actions as Discriminated Union
- Put in orderBuilding Context + useReducer
- Coding taskPractice: Context + useReducer
- Click in orderCustom Hook with Context Validation
- Put in orderDispatch Type in useReducer
- Put in orderFrom Simple to Complex Typing
- Put in ordercreateContext Syntax with a Type
- Click in orderTyped Reducer Definition
- Put in orderData Flow in Context + useReducer
- Put in orderCalling dispatch with an Action
- Click in orderTyped Provider Component
- Put in orderBenefits of TypeScript in React
- QuestionExhaustive Checking with never
- Coding taskPractice: Combining All Concepts