Search⌘ K

Creating a complex strongly-typed context for function components

Explore how to create and manage a complex strongly typed context in React function components using TypeScript. This lesson shows how to define an explicit context type, provide a context value with state and update functions, and integrate theme changes through a typed context provider and consumer components.

Explicitly setting the context type #

In this lesson, we are going to enhance the context from the last lesson so that the theme can be updated by consumers.

In the last lesson, the type for the context was inferred from the default value, which was a simple string. The type for our enhanced context is going to be a little more complex:

type ThemeContextType = {
  theme: string;
  setTheme: (value: string) => void;
};

So, there will be a theme property containing the current value for the theme and a setTheme method to update the current theme.

React’s createContext function expects us to supply a parameter for initial context value. We can supply a default value for the theme ...