Search⌘ K
AI Features

Creating a simple strongly-typed context for function components

Explore creating strongly-typed React context for function components with TypeScript. Learn to set up a theme context, provide it via a custom provider, and consume it with a custom hook. This lesson helps you share data across component trees while ensuring type safety and clarity.

Understanding React context #

React context allows several components in a tree to share some data. It’s more convenient than passing the data via props down the component tree.

The context is provided at a point in the component tree, and then all the children of the provider can access the context if they wish.

Creating a context #

A common use case for using context is to provide theme information to components in an app. We are going to provide a color value in a context that components can use.

Let’s start by creating our theme using Reacts createContext function:

const defaultTheme = "white";
const ThemeContext = React.createContext(defaultTheme);

We are ...