The Context Provider

The Provider is a component provided by React that allows its child components to subscribe to a certain context. It accepts a value prop which is the data that will be shared with all components that are consumers of that context.

Typically, you wrap the top-level component of your application with a Provider component, thus making the context available to all its descendants.

Javascript




// Context creation
const MyContext = React.createContext();
 
// Top-level Provider
const App = () => {
    return (
        <MyContext.Provider value={"Hello"}>
            <ChildComponent />
        </MyContext.Provider>
    );
};


What are Provider and Consumer in the Context API ?

Context API is a term that is created to pass as a global variable and can be accessed anywhere in the code. It is another way to pass props from child to parent i.e. known as “prop drilling“. It has two main components “The Context Provider ” and “The Context Consumer“.

Table of Content

  • The Context Provider
  • The Context Consumer
  • How to create context API ?
  • Conclusion

Similar Reads

The Context Provider:

The Provider is a component provided by React that allows its child components to subscribe to a certain context. It accepts a value prop which is the data that will be shared with all components that are consumers of that context....

The Context Consumer:

...

How to create context API ?

The Consumer is a component that allows components to subscribe to a context. It lets you access the context value and use it within your component’s render function....

Conclusion:

...