How to Use React Context with TypeScript

React Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Use it when you need to share data “globally”, between many components on different levels to a component tree.

Creating a Context#

To create a context use React.createContext:

With TypeScript, you can declare a type for a context, so that TypeScript will know what types are acceptable for this context.

However, there is a catch. If we have a data structure that can't have default values we can't just type a context:

There are 2 workarounds here.

  1. Use Partial<> utility type.

  2. Allow null as a fallback type.

The first one allows not to assign values to fields of a User type. So when we pass a defaultUser as an initial value there no errors:

But in this case, we lose in type-safety a bit because we can miss some values later.

The second option is to set null as an initial value:

This way we don't lose in type-safety, but we will need to check if the context value is null every time we access it.

Providing Context Values to Components#

When created, a context can be used in components. To give access to a context value we need to use Provider:

The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider.

Consuming Context Values via Consumer#

To get a value we need to use the Consumer component:

It uses a render-prop pattern. This means that it accepts a function instead of a component as a child. It will then pass a context value as an argument to this function.

Consuming Context Values via Hooks#

You can also use useContext hook to get access to a context value. This makes the component's source much simpler and cleaner.

Sources#