I was exploring useContext react hook by going through this video
In this video, what they have done is basically create a context
context.js
import { createContext } from "react";
export const CustomerContext = createContext(null);
And pass those context to child component
import Table from "./components/table";
import React, { useState } from "react";
import { CustomerContext } from "./context";
const App = () => {
const [user, setUser] = useState(null);
return (
<div>
<p> Hello World</p>
<CustomerContext.Provider value={{ user, setUser }}>
<Table />
</CustomerContext.Provider>
</div>
);
};
export default App;
And then in the child component access the value or change the value
import { CustomerContext } from "./../context";
import React, { useContext } from "react";
const Table = () => {
const { user, setUser } = useContext(CustomerContext);
return (
<div>
<p onClick={() => setUser("Rohit")}>Current User: {user}</p>
</div>
);
};
export default Table;
This could've also been achieved by simply passing the state as props to the child component.
So what is the advantage of using useContext? or maybe I misunderstood the video.
Can someone help me out here?
It avoid prop drilling. Passing data through props when you have 4 or 5 nested components is awful, and that's just a small case. Context will allow you to get your data from wherever you want in your application, but also provide a good way to manage it with other method like dispatch or useReducer.
Also, the ContextApi provided by React allow you to create multiple context to separate your concern which is pretty cool I think when you have a lot of data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With