JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext

Learn the concept

Context API

react
mid
context

What is React Context and when should you use it?

context
useContext
state-management
prop-drilling
providers
Quick Answer

Context provides a way to pass data through the component tree without prop drilling. Use it for global data like themes, authentication, or locale. For frequently changing data or complex state logic, consider state management libraries instead.

Detailed Explanation

What Context Solves:

  • Prop drilling: passing props through many levels
  • Global data that many components need
  • Data that doesn't change frequently

How Context Works:

  1. Create context with createContext()
  2. Wrap tree with Context.Provider
  3. Consume with use(Context) (React 19+, preferred) or useContext() hook

When to Use Context:

  • ✅ Theme (dark/light mode)
  • ✅ Current user/authentication
  • ✅ Locale/language preferences
  • ✅ Feature flags

When NOT to Use Context:

  • ❌ Frequently changing data (causes re-renders)
  • ❌ Complex state with many actions
  • ❌ Server state (use React Query, SWR)
  • ❌ When prop drilling is only 2-3 levels

React 19 Update:

  • use(Context) is preferred over useContext() — it can be called conditionally (inside if/else and loops)
  • React Compiler automatically memoizes context values, reducing need for manual useMemo optimization

Code Examples

Basic Context setupJSX
import { createContext, useContext, useState } from 'react';

// 1. Create context with default value
const ThemeContext = createContext('light');

// 2. Create provider component
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  
  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };
  
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 3. Custom hook for consuming (recommended)
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

// 4. Use in components
function ThemedButton() {
  const { theme, toggleTheme } = useTheme();
  return (
    <button 
      onClick={toggleTheme}
      style={{ background: theme === 'dark' ? '#333' : '#fff' }}
    >
      Current: {theme}
    </button>
  );
}

Real-World Applications

Use Cases

Theme Provider

Providing theme configuration (colors, fonts, spacing) to all components without prop drilling

Authentication Context

Sharing user auth state (token, user info, permissions) across the entire app

Internationalization

Providing locale and translation functions to all components via context

Mini Projects

Multi-Theme App

beginner

Build an app with context-based theme switching (light/dark/system) with CSS variable integration

Feature Flag System

intermediate

Create a context-based feature flag provider that conditionally renders features based on user roles

Industry Examples

Next.js

Uses React Context internally for router state and layout composition

Styled Components

Uses context for theming via ThemeProvider

Resources

React Docs - useContext

docs

React Docs - Passing Data Deeply with Context

docs

Related Questions

What are custom hooks and how do you create them?

mid
hooks
Previous
Explain the useState and useEffect hooks and their common patterns.
Next
What are custom hooks and how do you create them?
PrevNext