Context API is built-in state management for React Projects.Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In Simple React application, data pass through props from One component to another component. But what if we want to pass data to the bottom level of the component? Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
When to Use the Context API ?
Context is used to share data that can be considered “global” for a tree of React components used in current authenticated user, theme, or preferred language.
Using context, we can avoid passing props through intermediate elements. Context is primarily used when some data needs to pass on nesting levels.
In above given example,Main Component pass data through props to Layout component and layout passing data to Name component using name props from its parent component.
It might feel redundant to pass down the user prop through many levels if in the end only the Name component really needs It.
How to use Context
In React Context API, you should be familiar with :-
React.createContext is used to initialise the Context and it’s passed the initial value. It returns an object with a Provider and a Consumer. Providers and consumers come in pairs, that is, for each provider, there is a corresponding consumer.
const Context = React.createContext();
The Provider component is used higher in the tree and accepts a prop called value.It provides a root upon which any child in that tree can access the values that are provided by that context provider.
The provider accepts a context value as a prop. Any matching consumer in the provider’s subtree can access it, regardless of how deeply it’s nested.
The Consumer as the name suggests consumes the data being passed and renders the data by using a render prop API.
Implementation of Context Api
You will see that we have a state in Main Component that we will want to pass to Name. We have our static property that will allow us to declare what we want our context to be. In our case, the name “login user name”.
The Provider is holding on to that data so that when it’s consumed by another component, it knows what to give it. In our Lowest component you will see that we have the Consumer wanting that data without having to first pass it to the Layout component. That component instead just hangs out, declaring that Lowest is it’s child.