Lesson 5 of 8
Context API - Typed Global State
The React Context API allows sharing state across the component tree without prop drilling. With TypeScript, the context value type is generic. A common pattern protects against using the context outside its provider by initialising with `null` and asserting non-null in a custom hook.
Typed Context - Null Pattern & Strict Access
// ── Context typed from the start ────────────────────────────
interface TaskContextValue {
tasks: Task[];
loading: boolean;
error: string | null;
createTask: (input: Pick<Task, "title" | "priority">) => Promise<void>;
updateTask: (id: number, changes: Partial<Task>) => Promise<void>;
deleteTask: (id: number) => Promise<void>;
refetch: () => Promise<void>;
}
// ── null initialisation - protects against Provider-less usage ─
const TaskContext = React.createContext<TaskContextValue | null>(null);
// ── Provider component - encapsulates the state ───────────────
interface TaskProviderProps { children: React.ReactNode; }
export function TaskProvider({ children }: TaskProviderProps): React.ReactElement {
const [tasks, setTasks] = React.useState<Task[]>([]);
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
const refetch = React.useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await taskApi.getAll();
setTasks(data);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Failed to load tasks");
} finally {
setLoading(false);
}
}, []);
React.useEffect(() => { void refetch(); }, [refetch]);
const createTask = React.useCallback(async (
input: Pick<Task, "title" | "priority">
) => {
const created = await taskApi.create(input);
setTasks((prev) => [...prev, created]);
}, []);
const updateTask = React.useCallback(async (id: number, changes: Partial<Task>) => {
const updated = await taskApi.update(id, changes);
setTasks((prev) => prev.map((t) => (t.id === id ? updated : t)));
}, []);
const deleteTask = React.useCallback(async (id: number) => {
await taskApi.delete(id);
setTasks((prev) => prev.filter((t) => t.id !== id));
}, []);
const value: TaskContextValue = React.useMemo(
() => ({ tasks, loading, error, createTask, updateTask, deleteTask, refetch }),
[tasks, loading, error, createTask, updateTask, deleteTask, refetch],
);
return <TaskContext.Provider value={value}>{children}</TaskContext.Provider>;
}
// ── Custom hook - safe context access ────────────────────────
export function useTaskContext(): TaskContextValue {
const context = React.useContext(TaskContext);
if (context === null) {
throw new Error("useTaskContext must be used within <TaskProvider>");
}
return context; // TypeScript narrows to TaskContextValue (not null)
}
// ── Usage ────────────────────────────────────────────────────
function TaskList(): React.ReactElement {
const { tasks, loading, deleteTask } = useTaskContext();
if (loading) return <p>Loading...</p>;
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
{task.title}
<button onClick={() => void deleteTask(task.id)}>Delete</button>
</li>
))}
</ul>
);
}Common Mistakes
- Initialising context with a default non-null value - `createContext<TaskContextValue>({ tasks: [], ... })` hides the 'used outside Provider' bug. It silently returns stale defaults. Use `null` initial and throw in the hook.
- Not memoising context value - passing an inline object to `Provider value={{ ... }}` creates a new reference every render, re-rendering ALL consumers. Always wrap with `useMemo`.
- Putting all state in one giant context - separate concerns into smaller contexts (AuthContext, ThemeContext, TaskContext). One massive context means every consumer re-renders when any state changes.
Tip
Tip
Practice Context API Typed Global State in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Context API - Typed Global State
Practice Task
Note
Practice Task - (1) Write a working example of Context API Typed Global State from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Context API Typed Global State is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- The React Context API allows sharing state across the component tree without prop drilling.
- Initialising context with a default non-null value - `createContext<TaskContextValue>({ tasks: [], ... })` hides the 'used outside Provider' bug. It silently returns stale defaults. Use `null` initial and throw in the hook.
- Not memoising context value - passing an inline object to `Provider value={{ ... }}` creates a new reference every render, re-rendering ALL consumers. Always wrap with `useMemo`.
- Putting all state in one giant context - separate concerns into smaller contexts (AuthContext, ThemeContext, TaskContext). One massive context means every consumer re-renders when any state changes.
Finished this lesson?