DEV Community

Cover image for Why to use useContext?
Aastha Pandey
Aastha Pandey

Posted on

Why to use useContext?

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>
  );
}

Enter fullscreen mode Exit fullscreen mode
//Home.js
import React from "react";
import About from "./About";
const Home = ({count}) => {
 return (
    <>
      Home
      <hr />
      <About count = {count}/>
      </>
  );
};

export default Home;

Enter fullscreen mode Exit fullscreen mode
//About.js
import React from "react";

const About = ({count}) => {
 return <>
About
<hr/>
{count}
</>;
};

export default About;

Enter fullscreen mode Exit fullscreen mode

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>
  );
}

Enter fullscreen mode Exit fullscreen mode
//Home.js
import React from "react";
import About from "./About";
const Home = () => {
  return (
    <>
      Home
      <hr />
      <About />
    </>
  );
};

export default Home;

Enter fullscreen mode Exit fullscreen mode

import React from "react";
import { CountContext } from "./App";
const About = () => {
  const { count } = React.useContext(CountContext);
  return <>About
   <hr />
      {count}
      </>;
};

export default About;

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)