Introduction
According to the React documentation, React context allows us to pass data down the component tree without manually passing props at each level.
Earlier, we had to utilize the render prop pattern with class components, due to which the old Context was a pain to use, and it was always labeled unstable/experimental.
Things are now very straightforward thanks to the introduction of Hooks, notably the useContext Hook.
After you've created a context, all you have to do now is:
const userName = useContext(UserContext); |
React published the Context API(Application Programming Interface) as a much-needed solution for state that spans numerous nested components. Regrettably, the context API was a bit cumbersome and difficult to use in class components. With hooks release, the React team opted to rethink how you interact with context and utilize the useContext hook to simplify the code greatly.
Also See, Dropdown in React JS, Hooks in React JS
Upgrade your skill set with our react js course and become a sought after developer in today’s tech industry.
What is Prop-drilling?
Prop drilling is the process of moving props from one part of a tree to another in a React application by passing them via elements of the tree that don't require the data but just aid in their passage.
Let us take an example without using {useContext}.
import React from "react";
export default function Application() {
const name = "Coding Ninjas";
return <Hello name={name} />;
}
function Hello(props) {
return (
<div>
<h1>Hello Everyone!</h1>
<Greeting name={props.name} />
</div>
);
}
function Greeting(props) {
return "Welcome to " + props.name;
}
OUTPUT:
Context API
React uses state to store data and props to pass data across components. This is useful for passing simple props between parent and child components as well as handling local state. This system breaks down when you have a global state or props that need to be provided to deeply nested components. With only props and state, you'll have to resort to prop drilling, which entails routing props through several different components for them to reach a single component farther down the hierarchy.
The Context API comes into play here. You can provide specific pieces of data that will be exposed to all components nested inside the context using the context API, eliminating the need to transmit this data across each component. It's basically a semi-global state that may be accessed from anywhere within the context.
Without transmitting data through props manually, the Context API may be used to communicate data with different components. For example, the Context API is appropriate for the following use cases: theming, user language, authentication, and so on.
To initialize the context: createContext
We will first create the context to use it later for the provider and the consumer.
Example: To create a ‘ContextThemeHere’ for the React application’s theme.
import React from 'react';
// To pass the theme default value as 'light'
const ContextThemeHere = React.createContext('light');
export default ContextHere;
Although the createContext function accepts an initial value, it is not needed.
After you've created your context, it now has two React components: Provider and Consumer, which will be used further.
Create Provider
Providers are used to send a context value to the tree beneath them. Any component rendered inside the Provider, no matter how deep in the tree, can read its value. Let us look at an example:
/*
To provide the theme default value as 'light' to the
components rendered inside Application
*/
<ContextThemeHere.Provider value = "light">
<Application>
</ContextThemeHere.Provider>
Create Consumer
Consumers are used to determining the worth of a context. As a child, these require a function that gets the current context value and returns a React node:
<ContextThemeHere.Consumer>
{theme => <span>{value}</span>
/*The ‘theme’ is the context value that can be used by JSX in
this case*/}
</ContextThemeHere.Consumer>
We can have as many consumers as we want for a single context. All consumers are immediately alerted and re-rendered if the context value changes (by altering the ‘value’ prop of the provider <Context.Provider value={value} />).
If the consumer isn't wrapped in the provider but still tries to access the context value (through useContext(Context) or <Context.Consumer>), the context's value is the default value argument passed to the createContext(defaultValue) factory function that created the context.