Well, React official documentation says Contexts provide a way to route data through the component tree without having to manually propagate props at each level.
Think about a scenario in which several separate components at various degrees of nested levels need to access the same data. Data must be sent as props to the component tree when using React so that any component that requires it may access it.
Parent components can send data to nested child components in this way. They use many layers of components to transfer data from one piece to another.
Props drilling is a challenge when data must be routed across numerous features because specific parts get the braces and then pass them on to their child components as props.
Level 1 – Parent Component (App.js):
import React, { Component } from "react";
import ReactDOM from "react-dom";
import UserProfile from "./UserProfile.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: ""
};
}
render() {
return (
); } } constrootElement = document.getElementById(“root”); ReactDOM.render(, rootElement);
Level – 2 UserProfile.js
import React from "react";
import CurrentUserProfile from "./CurrentUserProfile.js";
constUserProfile = props => {
return (
); }; export default UserProfile;
Level – 3 CurrentUserProfile.js
import React from "react";
constCurrentUserProfile = props => {
return (
{props.currentUser}
); }; export default CurrentUserProfile;
The nested components in the preceding example have three layers. The nested element is receiving currentUser information as a prop. The CurrentUserProfile component receives data from the UserProfile component via props.
The UserProfile component does not use the props data in its way. After three layers of nesting components, examine the situation where many merely pass the props to their children. In extensive applications, this may be a significant problem.
This is where the React Context API comes into play. Context makes it possible to communicate values like these without passing a prop up and down the component hierarchy. For a tree of React components, context offers data that may be deemed globally accessible without explicitly supplying data to each inner part.
The previous example may readily be converted to Context-based. The present component does not require a complete overhaul. Only a few replacement parts are needed (provider and consumer).
Step-1: Initialize the Context
We are developing a framework in which suppliers and consumers may thrive.
constContextObject = React.createContext(defaultValue)
createContext() method is used to create a context. You can also pass the default value to the context variable by passing it to the createContext().
UserContext.js:
import React from "react";
constUserContext = React.createContext({});
export default UserContext;
This Context object’s current value will be retrieved by React when it displays a component that subscribes to this Context object. When a provider cannot be found in the tree, the default value of context is used.
Step – 2: Create the Provider:
Two Provider and Consumer Components are created when we create context. We can develop Provider and Consumer components, export them, and let other members utilize them as needed.
This is what UserContext.js would look like after constructing Provider and Consumer import React from “react”;
Creating context gives us two Provider and Consumer Components. We can create Provider and Consumer components and export them so that they are available for the other components to use them.
// this is the equivalent to the createStore method of Redux
constUserContext = React.createContext();
// creating Provider and Consumer and exporting them
export constUserProvider = UserContext.Provider
export constUserConsumer = UserContext.Consumer
export default UserContext;
No matter at what level this context is used, the Provider must be wrapped around the parent component. Using the Provider, I’ll encapsulate App.js and send userCurrent to the down tree.
App.js:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import UserProfile from "./UserProfile.js";
import { UserProvider } from "./UserContext.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: {
name: "Mr.Willey",
address: "USA",
mobile: "+1 (850) 780-1313"
}
};
}
render() {
return (
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);
The nested child receives the currentUser information from the parent. We’re getting our information about current users from the state.
We can get API information about a user and then pass it on to the child components that utilize that information. Wrapping userprofile in a provider imported from UserContext.js is what we’re doing.
The currentUser object may be accessed by any nested part. When the provider’s value changes, any consumers nested in it must re-render.
Step – 3: Create the Consumer:
In UserContext.js, we’ve already written code to consume it. Wrapping the child component in the Consumer for Class component and using the useContext method of React to access context information is the most straightforward approach to get access to the context. We can then use props to get at the context value sent in earlier in the process.
Using the prior illustration as a guide:
(without using context one),
UserProfile.js:
import React from "react";
import CurrentUserProfile from "./CurrentUserProfile.js";
constUserProfile = props => {
return ( ); };
export default UserProfile;
CurrentUserProfile.js:
(access the Context value.)
import React, { useContext } from “react”;
//importing UserContext from UserContext.js file
import { UserContext } from “./UserContext.js”;
constCurrentUserProfile = () => { const user = useContext(UserContext);
return (
{user.name}
{user.address}
{user.mobile}
);
}
}
)};
export default CurrentUserProfile;
Getting data from component A to component Z by passing it to multiple layers of components. As Data has to be passed through multiple components, this problem is called Props drilling. Because some components only just get the props and pass them to the child component as props. Below is an example of the above scenario.
Conclusion:
This is how to utilize react context API with class and functional components. Professional react js development services offered by Bosc Tech are helpful to know how to use react context API with functional and class components. Hope, this will help.
Hire React Developer Today!