Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this part, we will learn about React useContext hook, useContext is a basically a method with which you can access data from the context, or you can say some file. To perform this, we need to use context API.
It is the library which helps us to fetch data or to transfer data from one component to other component.
In react, data transfer is a big headache because if we need to transfer data like to Class A to Class D and also between them Class B and Class C is present then we have to use props among all classes where these props are useless to Class B and Class C.
To solve out this kind of situation, we have Context API which allows to Class A to communicate with Class D directly. We will learn in depth in future article about context API.
import {createContext} from "react";
const Create = createContext();
This is the syntax of context API to import it, also we have here imported createContext package, and we have defined a constant Create in this we have called the createContext() method.
Context is a method to transfer data or information through the tree of components without sending props manually down through every nested component. It’s specifically designed to share data that could be considered general data for the tree composed of React components, like the user’s current authentication status or theme(e.g., color, paddings, margins, font sizes). We will see how context and context API works later on.
In order to fetch data from the lowest child component, we need to use props in every component. To avoid this pain, we use React useContext hook.
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";
const UserContext = createContext();
function Component1() {
const [user, setUser] = useState("React Guru");
return (
<UserContext.Provider value={user}>
<h1>{`Hello ${user}!`}</h1>
<Component2 user={user} />
</UserContext.Provider>
);
}
function Component2() {
return (
<>
<h1>Component 2</h1>
<Component3 />
</>
);
}
function Component3() {
return (
<>
<h1>Component 3</h1>
<Component4 />
</>
);
}
function Component4() {
return (
<>
<h1>Component 4</h1>
<Component5 />
</>
);
}
function Component5() {
const user = useContext(UserContext);
return (
<>
<h1>Component 5</h1>
<h2>{`Hello ${user} again!`}</h2>
</>
);
}
export default Component1
As you can see in the above example, we have the bunch of components which calls next components, here we have need to do is to pass the data from component 1 to component 5 for that we are using provider here, so component 2, component 3, component 4 passes the data to component 5. Also, we have useContext hook in component 5 which will access the UserContext came from component 1.
Consider watching this video reference: