1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usecontext Hook
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
19Mins
41Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usecontext Hook

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
19Mins
41Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useContext Hook

Overview

If <ThemeContext.Provider> is the radio tower broadcasting the signal, the `useContext` hook is the radio receiver inside your component tuning into that exact frequency.

Prior to React Hooks, consuming context was incredibly ugly. You had to use a complex pattern called 'Render Props' with a <Context.Consumer> component, which created massive blocks of nested, hard-to-read code.

The useContext hook revolutionized this. By simply passing the original Context object (the one you created with createContext) into the hook, it instantly reaches up the component tree, finds the nearest matching Provider, and returns the data currently held in its value prop.

Syntax

Consuming Context
javascript
import { useContext } from 'react';
// We must import the exact Context object that was created elsewhere
import { ThemeContext } from './App';

function DeeplyNestedButton() {
  // We call the hook and pass it the specific Context object.
  // React travels UP the tree, finds <ThemeContext.Provider value="dark">
  // and assigns the string "dark" to the theme variable.
  const theme = useContext(ThemeContext);

  return (
    <button className={`btn-primary bg-${theme}`}>
      Submit
    </button>
  );
}

Common Pitfalls

  • Forgetting to Export the Context: You create const UserContext = createContext() in App.jsx. In Profile.jsx, you write useContext(UserContext) and get an error: 'UserContext is not defined'. You must explicitly export the context object from the file it was created in, and import it into the file where it is consumed.

Interview Questions

If there are multiple Providers for the same Context in a tree, which one does useContext read from?

useContext always reads from the closest matching Provider above it in the component tree. This allows you to override context for specific sections of your app (e.g., wrapping a specific sidebar in a 'dark' theme provider, while the rest of the app reads from a 'light' theme provider).

How do you consume multiple different contexts in a single component?

You simply call the hook multiple times. E.g., const theme = useContext(ThemeContext); const user = useContext(UserContext);. This is infinitely cleaner than the old Consumer wrapper pattern.

Real-World Example

Creating a Custom Context Hook: By creating a useAuth() custom hook, consumers don't need to know anything about useContext or the underlying AuthContext object. They just call one simple hook and get the data, with built-in error handling.

example
javascript
// Instead of forcing every component to import useContext AND AuthContext,
// it is an industry standard to export a custom hook from the context file itself.

import { createContext, useContext } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) { /* ... */ }

// Custom Hook: The ultimate clean API for consumers
export function useAuth() {
  const context = useContext(AuthContext);
  
  // Developer Experience: Throw a helpful error if they forgot the Provider!
  if (context === null) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  
  return context;
}

// IN ANY COMPONENT:
// import { useAuth } from './AuthContext';
// const { user, logout } = useAuth();

Check Your Knowledge

Test your understanding of useContext Hook with these quick questions.

Question 1

What must you pass as an argument to the `useContext` hook?

Question 2

How does `useContext` resolve its value?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useContext Hook

Overview

If <ThemeContext.Provider> is the radio tower broadcasting the signal, the `useContext` hook is the radio receiver inside your component tuning into that exact frequency.

Prior to React Hooks, consuming context was incredibly ugly. You had to use a complex pattern called 'Render Props' with a <Context.Consumer> component, which created massive blocks of nested, hard-to-read code.

The useContext hook revolutionized this. By simply passing the original Context object (the one you created with createContext) into the hook, it instantly reaches up the component tree, finds the nearest matching Provider, and returns the data currently held in its value prop.

Syntax

Consuming Context
javascript
import { useContext } from 'react';
// We must import the exact Context object that was created elsewhere
import { ThemeContext } from './App';

function DeeplyNestedButton() {
  // We call the hook and pass it the specific Context object.
  // React travels UP the tree, finds <ThemeContext.Provider value="dark">
  // and assigns the string "dark" to the theme variable.
  const theme = useContext(ThemeContext);

  return (
    <button className={`btn-primary bg-${theme}`}>
      Submit
    </button>
  );
}

Common Pitfalls

  • Forgetting to Export the Context: You create const UserContext = createContext() in App.jsx. In Profile.jsx, you write useContext(UserContext) and get an error: 'UserContext is not defined'. You must explicitly export the context object from the file it was created in, and import it into the file where it is consumed.

Interview Questions

If there are multiple Providers for the same Context in a tree, which one does useContext read from?

useContext always reads from the closest matching Provider above it in the component tree. This allows you to override context for specific sections of your app (e.g., wrapping a specific sidebar in a 'dark' theme provider, while the rest of the app reads from a 'light' theme provider).

How do you consume multiple different contexts in a single component?

You simply call the hook multiple times. E.g., const theme = useContext(ThemeContext); const user = useContext(UserContext);. This is infinitely cleaner than the old Consumer wrapper pattern.

Real-World Example

Creating a Custom Context Hook: By creating a useAuth() custom hook, consumers don't need to know anything about useContext or the underlying AuthContext object. They just call one simple hook and get the data, with built-in error handling.

example
javascript
// Instead of forcing every component to import useContext AND AuthContext,
// it is an industry standard to export a custom hook from the context file itself.

import { createContext, useContext } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) { /* ... */ }

// Custom Hook: The ultimate clean API for consumers
export function useAuth() {
  const context = useContext(AuthContext);
  
  // Developer Experience: Throw a helpful error if they forgot the Provider!
  if (context === null) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  
  return context;
}

// IN ANY COMPONENT:
// import { useAuth } from './AuthContext';
// const { user, logout } = useAuth();

Check Your Knowledge

Test your understanding of useContext Hook with these quick questions.

Question 1

What must you pass as an argument to the `useContext` hook?

Question 2

How does `useContext` resolve its value?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A