JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
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 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

Code Examples

Basic Context setup
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>
  );
}

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?