Creating a complex strongly-typed context for function components

In this lesson, we'll learn how to implement a strongly-typed context where consumers can change values within it.

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 property, but it doesn’t make sense to provide a default implementation for the setTheme method. So, a simple approach is to pass in undefined as the initial value:

const ThemeContext = React.createContext(undefined);

What do you think is the inferred type for the context value in this case?

Get hands-on with 1200+ tech skills courses.