Using context
The context API is designed to contain data that is common for a number of components in the application. Data in top-level context can be considered global.
Creating context
The context object will be required to both write and read data in the context. It's best to have it in a separate file.
The createContext
method takes an optional default value and returns the context object that contains both the provider
(write data) and consumer
(read data) bits:
Using the context
The easiest way to use context is the useContext
hook:
Given the Context object created earlier, the useContext
hook returns the current context's value.
Providing values
The above code will work without any modifications - it will just show the default value provided when creating the context.
Using the Context.Provider
component its possible to provide a different value:
Resources
Last updated