Typing Context with State and Dispatch
What you'll learn: How to properly type a context object that includes both state values and their setter functions from useState.
When you store useState values in context, you're not just passing data—you're passing both the current state and the functions to update it. TypeScript needs to know the shape of this combined object.
The Pattern
Your context type should describe the entire state/setter pair:
interface ThemeContextType {
theme: 'light' | 'dark';
setTheme: (theme: 'light' | 'dark') => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
Why Both?
Think of context like a toolbox: you need both the current tool (state) and the ability to swap tools (setter). By typing both together, consumers get full access with complete type safety.
The Setter Function Type
The setter type (theme: 'light' | 'dark') => void matches what useState returns. TypeScript infers this automatically, but being explicit in your interface ensures consumers know exactly what they can pass.
Common Pattern with Dispatch
This pattern becomes even more important when using useReducer, where you'd type the dispatch function alongside state—but that's context plus dispatch, using the same structural principle.
Key Takeaway: A context containing useState should type both the state value and its setter function as a single interface, ensuring consumers have fully-typed access to read and write operations.