Prop Drilling Vs Context API In React? See Example Guide

Prop Drilling vs Context API

  • Prop Drilling: Passing data through multiple component levels via props.
  • Context API: Provides global state accessible by any component in the subtree, avoiding prop drilling.

Prop Drilling Example

function Child({ name }) {
  return <h2>Child Name: {name}</h2>;
}

function Parent({ name }) {
  return <Child name={name} />;
}

function App() {
  const name = "Sagar";
  return <Parent name={name} />;
}

✅ Data passes through each level manually.


Context API Example

import React, { createContext, useContext } from "react";

const NameContext = createContext();

function Child() {
  const name = useContext(NameContext);
  return <h2>Child Name: {name}</h2>;
}

function App() {
  const name = "Sagar";

  return (
    <NameContext.Provider value={name}>
      <Child />
    </NameContext.Provider>
  );
}

✅ Child accesses data directly without intermediate props.


Key Points

FeatureProp DrillingContext API
Data PassingThrough props manuallyGlobal state via context
Use CaseSimple hierarchyDeeply nested components
MaintenanceHard to manage for many levelsEasier to maintain
FlexibilityLowHigh

Conclusion

Use Context API to avoid prop drilling and simplify state management for nested or global data.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *