This content originally appeared on DEV Community and was authored by Aastha Pandey
What made me use useContext? What would one normally do if they want to pass data down the tree to some component, they will achieve this by passing the data as props to the child components, I did the same thing until I got to know about useContext.
What if one wants to pass the count to the last child component in the tree, like in the below code from App component(Parent Component) to About component(Last Child Component).
Without using useContext
//App.js
import Home from "./Home";
import React from "react";
export default function App() {
const [count, setCount] = React.useState(0);
return (
<div className="App">
<Home count = {count}/>
</div>
);
}
//Home.js
import React from "react";
import About from "./About";
const Home = ({count}) => {
return (
<>
Home
<hr />
<About count = {count}/>
</>
);
};
export default Home;
//About.js
import React from "react";
const About = ({count}) => {
return <>
About
<hr/>
{count}
</>;
};
export default About;
With useContext
When we are using useContext we don't need to pass data to Home component in order to make it available to About component and we can use the count in any component which comes down the tree and is child of that component which is enclosed in Provider component.
//App.js
export const CountContext = React.createContext();
export default function App() {
const [count, setCount] = React.useState(0);
return (
<div className="App">
<CountContext.Provider
value={{
count
}}
>
<Home/>
</CountContext.Provider>
</div>
);
}
//Home.js
import React from "react";
import About from "./About";
const Home = () => {
return (
<>
Home
<hr />
<About />
</>
);
};
export default Home;
import React from "react";
import { CountContext } from "./App";
const About = () => {
const { count } = React.useContext(CountContext);
return <>About
<hr />
{count}
</>;
};
export default About;
The code won't do anything it'll just display a count on the screen that is 0.
Note: Context should be used to pass those data, which one wants to be displayed on every screen or common for all the pages like user name, theme, number of items in some cart etc.
This content originally appeared on DEV Community and was authored by Aastha Pandey
Aastha Pandey | Sciencx (2021-05-31T20:15:12+00:00) Why to use useContext?. Retrieved from https://www.scien.cx/2021/05/31/why-to-use-usecontext/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.