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

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
19Mins
43Secs
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

Context API

Overview

To solve the Prop Drilling problem without requiring third-party libraries, React provides a built-in feature called the Context API.

Context acts like a global teleportation wormhole. You wrap a high-level component (like <App />) in a Context Provider and feed it some data (like the user's theme or login status). Once provided, that data is instantly 'broadcasted' to the entire component tree below it.

Any component inside that tree, whether it is 1 level deep or 50 levels deep, can 'tap into' the wormhole and consume the data directly, completely bypassing all the components in between. When the Provider's data changes, React automatically re-renders every component that is actively consuming that specific context.

Syntax

Creating and Providing Context
jsx
import { createContext, useState } from 'react';

// 1. Create the Context (usually exported so others can import it)
export const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('dark');

  return (
    // 2. Wrap the application tree in the Provider.
    // The 'value' prop is the data you are broadcasting to the universe.
    <ThemeContext.Provider value={theme}>
      <div className="app-layout">
        {/* We NO LONGER pass theme as a prop! */}
        <Header /> 
        <MainContent />
      </div>
    </ThemeContext.Provider>
  );
}

Common Pitfalls

  • The Object Value Re-render Trap: If you pass an object inline into a provider: <Provider value={{ user, setUser }}>, React creates a brand new object in memory every single time the Provider re-renders. Because the memory reference changes, React forces EVERY component consuming the context to re-render, destroying performance. You must wrap objects in useMemo before passing them to value.

Interview Questions

What is the purpose of the default value in createContext(defaultValue)?

The default value is ONLY used if a component attempts to consume the context but there is NO matching <Provider> anywhere above it in the component tree. It is mostly used for testing components in isolation without having to wrap them in mock Providers.

Why shouldn't you use Context API for data that changes multiple times per second (like mouse position)?

The Context API is not optimized for high-frequency updates. Whenever the Provider's value changes, React traverses the tree to re-render every consumer. For rapidly changing data, specialized state managers like Zustand or Redux (which use selectors to prevent unnecessary renders) are required.

Real-World Example

Optimized Authentication Provider: In enterprise apps, you rarely expose the raw Provider in your App.jsx. You create an AuthProvider wrapper component that encapsulates the state logic, the memoization, and the provider itself, keeping App.jsx incredibly clean.

example
jsx
import { createContext, useMemo, useState } from 'react';

export const AuthContext = createContext(null);

// Best Practice: Abstract the Provider into its own component
export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  
  // Login function
  const login = (userData) => setUser(userData);
  const logout = () => setUser(null);

  // CRITICAL: We memoize the object so its memory address doesn't 
  // change on every render, saving our app from performance death!
  const contextValue = useMemo(() => {
    return { user, login, logout };
  }, [user]);

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  );
}

Check Your Knowledge

Test your understanding of Context API with these quick questions.

Question 1

What component must wrap your application tree in order to broadcast context data?

Question 2

What happens if a component tries to consume a context, but it is NOT wrapped inside a Provider?

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

Context API

Overview

To solve the Prop Drilling problem without requiring third-party libraries, React provides a built-in feature called the Context API.

Context acts like a global teleportation wormhole. You wrap a high-level component (like <App />) in a Context Provider and feed it some data (like the user's theme or login status). Once provided, that data is instantly 'broadcasted' to the entire component tree below it.

Any component inside that tree, whether it is 1 level deep or 50 levels deep, can 'tap into' the wormhole and consume the data directly, completely bypassing all the components in between. When the Provider's data changes, React automatically re-renders every component that is actively consuming that specific context.

Syntax

Creating and Providing Context
jsx
import { createContext, useState } from 'react';

// 1. Create the Context (usually exported so others can import it)
export const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('dark');

  return (
    // 2. Wrap the application tree in the Provider.
    // The 'value' prop is the data you are broadcasting to the universe.
    <ThemeContext.Provider value={theme}>
      <div className="app-layout">
        {/* We NO LONGER pass theme as a prop! */}
        <Header /> 
        <MainContent />
      </div>
    </ThemeContext.Provider>
  );
}

Common Pitfalls

  • The Object Value Re-render Trap: If you pass an object inline into a provider: <Provider value={{ user, setUser }}>, React creates a brand new object in memory every single time the Provider re-renders. Because the memory reference changes, React forces EVERY component consuming the context to re-render, destroying performance. You must wrap objects in useMemo before passing them to value.

Interview Questions

What is the purpose of the default value in createContext(defaultValue)?

The default value is ONLY used if a component attempts to consume the context but there is NO matching <Provider> anywhere above it in the component tree. It is mostly used for testing components in isolation without having to wrap them in mock Providers.

Why shouldn't you use Context API for data that changes multiple times per second (like mouse position)?

The Context API is not optimized for high-frequency updates. Whenever the Provider's value changes, React traverses the tree to re-render every consumer. For rapidly changing data, specialized state managers like Zustand or Redux (which use selectors to prevent unnecessary renders) are required.

Real-World Example

Optimized Authentication Provider: In enterprise apps, you rarely expose the raw Provider in your App.jsx. You create an AuthProvider wrapper component that encapsulates the state logic, the memoization, and the provider itself, keeping App.jsx incredibly clean.

example
jsx
import { createContext, useMemo, useState } from 'react';

export const AuthContext = createContext(null);

// Best Practice: Abstract the Provider into its own component
export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  
  // Login function
  const login = (userData) => setUser(userData);
  const logout = () => setUser(null);

  // CRITICAL: We memoize the object so its memory address doesn't 
  // change on every render, saving our app from performance death!
  const contextValue = useMemo(() => {
    return { user, login, logout };
  }, [user]);

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  );
}

Check Your Knowledge

Test your understanding of Context API with these quick questions.

Question 1

What component must wrap your application tree in order to broadcast context data?

Question 2

What happens if a component tries to consume a context, but it is NOT wrapped inside a Provider?

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