API Context:

Nimra KosarNimra Kosar
2 min read

What is API + Context in React?

Think of your React app like a house:

  • API → The delivery guy bringing data from outside (server).

  • Context → A central kitchen where you store the delivered food so anyone in the house can take it without asking the delivery guy again.

Normally, if you fetch API data inside one component:

  • That data stays there.

  • If another component needs it, you either pass it down as props (prop drilling, which is like handing the same plate through every room in the house — annoying) or fetch it again (wasteful).

With Context API:

  • You fetch once.

  • Put it in the Context (global storage).

  • Any component can open that “storage” and get the data instantly.


How it works step-by-step

  1. Create Context → This is like making the global storage space.

  2. Fetch data from API → Bring in the data and store it in that Context.

  3. Wrap your app in a Provider → This makes the storage accessible to all child components.

  4. Use useContext hook anywhere → Just “open the fridge” and grab the data.


Why use Context for API data?

  • No repeated fetching → You hit the API only once.

  • No prop drilling → You don’t need to pass data manually through many components.

  • Easier to maintain → If the API changes, update it in one place.


💡 Example in real life:
Imagine you’re making a weather app.
Without Context → Every component (home page, forecast page, sidebar) fetches the weather data separately.
With Context → Fetch once, store it, and share it with all components instantly.

0
Subscribe to my newsletter

Read articles from Nimra Kosar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nimra Kosar
Nimra Kosar