useContext
React Context is a way to manage state globally.It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.
Before useContext developers face the problem is prop drilling.prop drilling the data has to be passed every component through props even if middle component didnot need the data we had to pass them.
Example:
If the parent component(main) passes the data which need the last component.The main component passed the data app component ,the app component passed the data through home component, the home component passed the data through about componet, the about component passed the data contact component.The contact component used the data.This is called the prop drilling. Why this is an issue? Here in the middle there 3 or 4 components .In the other project in the middle 100 components we had to pass the props at each level.This could be the major headache.So, the solution is useContext.
There are 3 steps to use useContext
1.create context
2.Provide values
3.useContext
Step 1: Create a Context
First, we need to create a context using the createContext function. This can be done in a separate file for better organization:
import { createContext } from "react";
export const DashboardContext = createContext();
Step 2: Create a Context Provider
const [user, setUser] = useState({
name: "Zohaib"
});
return (
<DashboardContext.Provider value={user}>
<Dashboard />
</DashboardContext.Provider>
)
Step 3 – use the Context
import { useContext } from "react";
import { DashboardContext } from "./DashboardContext";
function Sidebar() {
const user = useContext(DashboardContext);
return <h2>{user.name}</h2>;
}
//{
name: "Zohaib"
}
References
https://medium.com/@zohaibshahzad16/mastering-reacts-usecontext-hook-with-a-practical-example-dbcdf772e1c2
https://namastedev.com/blog/usecontext/
https://dev.to/p-rf/understanding-the-react-usecontext-hook-and-how-to-use-it-3ph5
https://www.w3schools.com/react/react_usecontext.asp
Top comments (0)