DEV Community

Cover image for CreateContext

Posted on


Developers can construct a context object to use to transport data across a component tree using the CreateContext method supplied by the React library in JavaScript, eliminating the need to manually pass props down at each level. Data sharing across components that are not directly connected in the component tree is made possible by this.
Here's an example of how to create a context object:

Image description
The createContext method takes an optional default value as its argument, which will be used as the initial value for the context if a Provider is not present further up the component tree.

Once the context is created, it can be consumed by any component in the tree using the useContext hook or the Context.Consumer component.

Here's an example of how to use the context in a component:

Image description

The Context.Consumer component is a part of the React library. It is used to access the context data that has been provided by a Context.Provider component. The Context.Consumer component takes a single function as its child, which is called with the current context value. The function should return a React element, which will be rendered with the current context data.

For example, in the following code snippet, the ThemeContext.Consumer component is used to access the theme value provided by the ThemeContext.Provider component. The function passed as a child to the ThemeContext.Consumer component is called with the current theme value, and the returned element is rendered with the current theme.

Image description

To provide the context with a value, you can use the Context.Provider component.

Image description

In this example, the context value for  MyComponent component will be "Hello World." The context will also be used by any components lower down the tree that consume it. It is important to remember that you can use the context's Provider anywhere in the component tree, it doesn't need to be the parent of the component that uses the context.

You could also update the context value by using the state and setState Hooks

Image description

In this example, the value of the context will change to "New Value" when the button is clicked and all the components that are consuming the context will receive the new value.

To sum up, createContext is a powerful tool that allows data to be shared between components that are not directly connected in the component tree, it can be consumed with useContext or Context.Consumer and provided with Context.Provider and it allows the context value to be updated with state and setState hooks.

Top comments (0)