DEV Community

Cover image for The power of useContext hook
Dery L.
Dery L.

Posted on • Updated on

The power of useContext hook

Did you know that useContext can make your life easier?

For those who are not familiar with useContext, this is one of the magic wonders of React. This hook allows to share data (state) in any component of our app without using props. Basically it will re-render the state with the new update that was implemented.

Surprise reaction

How did it made my life easier?

I created recently a website where my components need to pass state between them and update the rendering. As you can imagine, this isn't code efficient because it can get messy.

For this, I created a file where all my data was implemented and I could pass a value to the context that is used in all my components. This is done by giving a value to the context as it shows in the example below:

import { createContext } from 'react';

const PizzaContext = createContext();

export function PizzaProvider({ children }){
    const [pizzas, setPizzas] = useState({
     pizza-ingredient-1: true
     pizza-ingredient-2: false
     pizza-ingredient-3: false
     pizza-ingredient-4: true
     pizza-ingredient-5: false
     ...
});

return (
        <PizzaContext.Provider value={{ pizzas }}>
            { children }
        </PizzaContext.Provider>
    )
}

export default PizzaContext;
Enter fullscreen mode Exit fullscreen mode

Then, in my App.js file I passed the context so it can render the new state every time it is updated.

import { PizzaProvider } from './PizzaContext';

const App = () => {

  return (
    <>
      <Header />
      <PizzaProvider>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/base" element={<Base />}/>
          <Route path="/sauce" element={<Sauce />} />
          <Route path="/topping" element={<Topping />} />
          ...
        </Routes>
      </PizzaProvider>
      <Footer />
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Thanks to this, the user will be able to update the state of every component and pass it to the following step with the item selected.

This is one of the many implementations that useContext can help us achieve the desired goal.

If you'd like to see the final result of the website, please be my guest and have a look here.

Top comments (0)