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
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.
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 component accepts a value prop to be passed to consuming components that are descendants of this
Consuming Context Values via
To get a va