React · Lesson 9 of 15 · 3 min
Context API & Custom Hooks for Reusability
This is how you manage shared state without prop drilling, a pattern you'll be expected to explain and implement in any mid-to-senior React interview.
Stop prop drilling with Context
Prop drilling is passing props through components that don't need them, just to get data to a deeply nested child. It’s brittle because refactoring any component in the chain can break data flow, and it adds noise to every intermediate component's props.
The Context API solves this. It creates a "tunnel" through your component tree. A Provider at the top puts a value into the context, and any descendant component can consume that value directly, no matter how deep it is.
Use Context for low-frequency updates of state that is truly global to a component tree: the current user, the UI theme, or the selected language. If a state changes often or is only needed by a direct child, props are simpler and more performant.
The Provider, the Value, and the Consumer
The pattern has three parts:
createContext(): Defines the "tunnel."MyContext.Provider: Wraps a part of your component tree and provides the sharedvalue.useContext(MyContext): The hook used by a child component to read the currentvalue.
This diagram shows how a Provider makes a value available to nested consumers, skipping the intermediate components.
Any component inside the ThemeProvider can call useTheme() and get the value 'dark'. The Layout, Header, and Sidebar components don't need to know about it.
The performance trap: a new value on every render
When the Provider's parent re-renders, React checks if the value prop has changed to decide if consumers should re-render.
The trap: If you pass an object or array created inline, it will be a new object on every render. This breaks the reference equality check (oldValue === newValue) and forces every single consumer of that context to re-render, even if the data inside the object is identical.
// Bad: A new object is created on every render of SomeParentComponent
return <ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
This is a significant performance bottleneck.
To fix it, memoize the context value. Use useMemo to ensure the value object's identity only changes when its underlying data changes.
// Good: The value object is stable across re-renders
const contextValue = useMemo(() => ({
theme,
toggleTheme
}), [theme, toggleTheme]);
return <ThemeContext.Provider value={contextValue}>
{children}
</ThemeContext.Provider>
Encapsulate state access with a custom hook
Never export the Context object itself. Instead, create a custom hook that wraps useContext and provides the context value. This is a critical pattern for creating a clean, maintainable API for your shared state.
This approach has three benefits:
- Abstraction: Components don't need to know about
useContextor which context they are consuming. They just calluseAuth(). - Safety: The custom hook can include a check to ensure it's being used within the provider, throwing a helpful error otherwise.
- Centralization: All logic related to the context is in one place, making it easier to modify or debug.
Here is a complete, minimal example for an authentication context.
import React, { createContext, useContext, useState, useMemo, ReactNode } from 'react';
interface AuthContextType {
userId: string | null;
login: (id: string) => void;
logout: () => void;
}
// 1. Create the context, but don't export it.
const AuthContext = createContext<AuthContextType | undefined>(undefined);
// 2. Create the provider component.
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [userId, setUserId] = useState<string | null>(null);
const login = (id: string) => setUserId(id);
const logout = () => setUserId(null);
// 3. Memoize the value to prevent unnecessary re-renders.
const value = useMemo(() => ({ userId, login, logout }), [userId]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
// 4. Create and export the custom hook.
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
Now, any component wrapped in <AuthProvider> can simply call const { userId, login } = useAuth(); to access the authentication state and functions.
When to use Context vs. a state management library
This is a classic system design question. The answer depends on the complexity and update frequency of your state.
How to answer: "I'd start with React Context for simple, low-frequency global state like user authentication or theme. It's built-in and easy to set up. If the application state becomes more complex, with many frequent updates from different sources, or if we need features like middleware for logging, time-travel debugging, or derived data selectors, I'd introduce a dedicated library like Zustand or Redux. They are optimized for performance with high-frequency updates and provide more powerful developer tools."
Don't treat Context as a free version of Redux. Its re-render behavior is different and less optimized for frequent changes to large state objects.
Try it
Take a small app you've built that passes a prop down three or more levels. Refactor it to use the Context API. Create a provider, wrap the component tree, and create a custom useMyFeature hook to access the shared state in the child component.
Next: Client-Side Routing with React Router.
Lock it in — apply this lesson under interview conditions.