useContext

Subject: React

๐Ÿ” What is useContext?

useContext is a React Hook that allows components to access global/shared data without prop drilling.

Think of it like a global variable โ€” any component can read from it, no matter how deep it is in the component tree.


๐Ÿ” Why Use useContext

Without ContextWith Context
Pass data parent โ†’ child โ†’ subchildAccess data directly in any component
Complex and repetitive prop chainsCleaner and more scalable
Tedious to update/apply globallySimple global data flow

๐Ÿ› ๏ธ Real Use Cases

  • Authenticated user info
  • Theme (light/dark)
  • Language (i18n)
  • App-wide preferences/settings
  • Combine with useReducer for global state

๐Ÿ“ฆ Basic Setup of Context


โœ… Example: Share User Data Across Components

UserContext.js

App.js

Dashboard.js


๐Ÿง  Logic Explained

StepDescription
createContext()Creates a Context object
ProviderMakes the value available to children
useContext(Context)Hook to read the value in any nested component
Value FlowParent โ†’ Provider โ†’ Any child component

โœ… Dynamic Updates with Context

Example:

Access + update from anywhere:


โš ๏ธ When NOT to Use Alone

  • For complex global state, combine with useReducer
  • Frequent context updates? โ†’ Use React.memo or split into smaller contexts

๐Ÿ“Œ Summary Table

FeatureDescription
createContext()Creates context container
ProviderWraps components and shares a value
useContext()Reads the shared value inside any component
AvoidsProp drilling
Best ForTheme, auth, user info, i18n, shared app settings

๐Ÿงช Real-Life Analogy

Context is like cloud storage:

  • Upload data once using a Provider
  • Any connected component ("device") can download it using useContext

๐Ÿ‘‰ Next: Explore useReducer โžก๏ธ