Props and state are essential parts of a React component. While the state is controlled within the component, props are passed to it from the parent component. In a huge React application, a global state is generally created to pass the data around. Through props can also be used to pass data around multiple components but that can lead to unwanted situations. To avoid such unwanted situations, React provides the Context API. In this article, we will discuss what Context API is and how (and why) it is used.
Why use Context API?
Before discussing what is the context API, let’s discuss why to use it. Suppose we have a React application with five components - ComponentA, ComponentB, ComponentC, ComponentD, and ComponentE. Following is the structure of the application.ComponentA
|
ComponentB
|
ComponentC
|
ComponentD
|
ComponentE
So here, ComponentB is the child of ComponentA, ComponentC is the child of ComponentB and so on.
Now suppose we have an object that we need to pass from ComponentA to ComponentE. How to do this? Create a global state using Redux? Well, Redux is generally used for complex state management in bigger React applications and this is not the situation in this example.
Another way is to pass the object from ComponentA to ComponentB and then from ComponentB to ComponentC and then from ComponentC to ComponentD, and finally from ComponentD to ComponentE. This method will work too but the object has an unnecessary presence in three components. Such passing of props is known as Prop drilling.
To avoid the usage of state management libraries and especially to avoid prop drilling, React provides Context API.
What is Context API?
In simple terms, Context API is a way using which data can be shared among components without passing it through props or creating a global state. So if there is an object in ComponentA, we can pass it directly to ComponentE without involving other components or redux.So let’s understand the Context API in React with the help of an example.
Observe the following component.
import ComponentB from "./ComponentB";
function ComponentA() {
const emp = {
name: "Johny",
age: 21,
city: "Chicago",
};
return <ComponentB />;
}
export default ComponentA;
“ComponentB” is the child of the above component. Similarly, “ComponentC” is the child of “ComponentB”. This is the structure we discussed earlier. So “ComponentE” is the last component in the tree.
“ComponentA” has an object named “emp” and we will use this object in “ComponentE” by using context API.
Let’s start by creating a context in a separate file.
import React from "react";
const AppContext = React.createContext();
export default AppContext;
```
We will use “AppContext” in “ComponentA”.
```
import ComponentB from "./ComponentB";
import AppContext from "./AppContext";
function ComponentA() {
const emp = {
name: "Johny",
age: 21,
city: "Chicago"
};
return (
<AppContext.Provider value={{ empDetails: emp }}>
<ComponentB />
</AppContext.Provider>
);
}
export default ComponentA;
“ComponentA” is a provider, so we have to wrap the component in “Provider” using the “AppContext”.
<AppContext.Provider value={{ empDetails: emp }}>
<ComponentB />
</AppContext.Provider>;
Here, we are passing “value” as an attribute. This attribute can be accessed in any component now. Let’s move to “ComponentE”.
“ComponentE” is the consumer. We can consume the value provided by the provider using two ways:
By using “Consumer” provided by context API.
By using useContext react hook.
The useContext hook is the easier and better way. So let’s use this hook to access the value in “ComponentE”.
import { useContext } from "react";
import AppContext from "./AppContext";
function ComponentE() {
const context = useContext(AppContext);
return <> </>;
}
export default ComponentE;
The “AppContext” is passed as an argument to useContext hook and saved in a variable. Let’s console the variable and see what it contains.
It contains the same object we defined in the “ComponentA”. Let’s access the values in “ComponentE” and check the output in the browser.
import { useContext } from "react";
import AppContext from "./AppContext";
function ComponentE() {
const context = useContext(AppContext);
return <>
<h1> Name: {context.empDetails.name} </h1>
<h1> Age: {context.empDetails.age} </h1>
<h1> City: {context.empDetails.city} </h1>
</>;
}
export default ComponentE;
Output:
This is how context API is used in React to pass the data.
Summary
Using Context API is easy and simple. First, we have to define a context API. Then, we have to wrap the provider component in a “Provider”. Using the “Provider” provided by context API, we have to specify the attribute that contains the data which is used to pass around.After that, in the consumer component, we have to use, either useContext hook or the “Consumer” provided by context API to access the value passed by the provider component.
Other React and Web development Articles and resources you may like
- 5 Projects to learn React.js better
- 10 Books and Courses to learn Angular
- FullStack React.js and Spring Boot Example
- My favorite free Courses to learn Angular and React
- My favorite books to learn React.js
- The 2022 React.js RoadMap for beginners
- The Frontend and Backend Developer RoadMap
- 10 Courses to learn AWS for beginners
- 5 Free Docker Courses for Java and DevOps Engineer
- 5 Online training courses to learn Angular for Free
- How to create React app using Redux and React Hooks
- 10 Reasons to learn React.js in 2022
- 5 Best courses to learn React Native
- 5 Courses to learn Object-Oriented Programming for Free
- 5 Free Courses to learn Kubernetes
- 3 Books and Courses to Learn RESTful Web Services in Java
Thanks for reading this article so far. If you like this React Context API tutorials, then please share them with your friends and colleagues. If you have
any questions or feedback, then please drop a comment.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.