


The third consumer is not a child of any of the providers so it will use the context’s default value. This means it is quite easy to override values for some parts of the application. The consumer component will use the first value provided above it in the tree. In the example below there are multiple providers with different values. Please note useContext can only be used in function components, and the same rules apply as with other hooks.Ī single context object can be assigned to a class component’s contextType property and accessed as ntext. If the value is an object, it can be easily deconstructed to separate constants. With the useContext hook, the context object is used as an injection token to access its value. The context object also exposes a Consumer component that calls its child function with the current value. There are three ways to access the provided data: Consumer component, useContext hook, and contextType. Any primitive value or object passed to this prop will be accessible in any child of this component. The context object we just created exposes a Provider component that has a prop named value. I will go into more detail in a bit about how scoping works. The returned object will contain helper components you need to provide or consume this context.ĭefault values are only used when you try to access context in a component where no provider is present above it in the component tree. Optionally provide an interface describing your provided object. This will be the default value provided to the consumers. To create a context, call the createContext function with an arbitrary value. There are no restrictions on what type of values you can provide, so you can easily pass in functions that can be used to communicate events back from consumers, for example. Overview of the API Creating a contextĪ context contains references to variables and notifies its consumers when these references are changed. Despite its low-level nature, it might be the perfect solution in some cases. It can be used to solve the same problems as Redux does, but it doesn’t provide a strict way of state manipulation to ensure predictable behavior. It makes it possible to pass data from parent to children nested deep down the component tree directly, instead of passing it down through a chain of props. IntroductionĬontext is a built-in API introduced in React 16.3. We are looking to expand our team with talented developers. Pardon the interruption, we have an important message!
