DEV Community

Cover image for useContext() in React . . .
_Khojiakbar_
_Khojiakbar_

Posted on

useContext() in React . . .

The Story of Captain Context and the Treasure Map

What is useContext?

Imagine you're on a pirate ship, and you're the captain. You have a treasure map, and everyone on your crew needs to see it to find the treasure. You could make copies of the map and give one to each crew member, but that would be a lot of work. Plus, what if the map changes? You’d have to update every single copy—what a headache!

Instead, you decide to hang the original map in the middle of the ship, where everyone can see it whenever they need to. No running around, no confusion—just easy access to the treasure map. In React, this central map is like useContext.

Why do we use useContext?

In a React app, different components often need access to the same "treasure map" (like user settings, themes, or data). Without useContext, you’d have to pass the map through each component individually, which gets really messy—like a captain passing a map from one crew member to the next across the entire ship.

With useContext, you hang the map where everyone can reach it directly. Now all your crew (components) can see the treasure map without you having to hand it to them one by one.

How do we use useContext?

  1. Create the Treasure Map (Context): First, you create the treasure map using createContext(). This is where the map’s details will be stored.
const TreasureMapContext = createContext();
Enter fullscreen mode Exit fullscreen mode

2.** Hang Up the Map (Provider):** Next, you hang the map in a visible place using a Provider. This Provider wraps around the parts of your ship (components) that need to see the map.

function PirateShip() {
  const treasureMap = "X marks the spot!"; // This is the map everyone will follow.

  return (
    <TreasureMapContext.Provider value={treasureMap}>
      <Deck />
      <CrowNest />
    </TreasureMapContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. Read the Map (useContext): Now, any crew member (component) can check the map directly using useContext.
function Deck() {
  const treasureMap = useContext(TreasureMapContext);

  return <p>Arr! The map says: {treasureMap}!</p>;
}

function CrowNest() {
  const treasureMap = useContext(TreasureMapContext);

  return <p>Aye! I see the spot from up here: {treasureMap}!</p>;
}
Enter fullscreen mode Exit fullscreen mode

Putting It All Together

Imagine your app is a pirate ship. You, the captain, have a treasure map that everyone on the ship needs. Instead of running around handing out copies, you hang the map up in a central place where everyone can see it. That’s useContext—a simple, efficient way to share important information across your entire app without the chaos of passing props everywhere.

Now, if your crew wants to find the treasure, they just take a peek at the map and sail straight to the gold!

Top comments (0)