Skip to main content

context hooks in react

Context hooks in React, primarily

useContext, allow functional components to subscribe to and consume data from React's Context API, simplifying global state management by avoiding "prop drilling" (passing props down many levels). You create a Context with React.createContext(), wrap parts of your app with a Provider to pass data down, and then use useContext(MyContext) in any nested component to read that data, making it ideal for themes, authentication, or user settings. 



Key Components

  1. React.createContext(): Creates a Context object, often with a default value, that components can subscribe to.
  2. <Context.Provider>: A component that wraps a part of your component tree and uses the value prop to provide data to all descendants.
  3. useContext(Context): A hook used in functional components to read the current context value from the nearest Provider above it in the tree. 

How It Works (Simplified)

  1. Create Context:
    javascript
  2. import { createContext } from 'react';
    const ThemeContext = createContext('light'); // Default value
    
  3. Provide Context: Wrap components with the Provider high up in the tree.
    javascript
  4. function App() {
      return (
        <ThemeContext.Provider value="dark">
          <Toolbar />
        </ThemeContext.Provider>
      );
    }
    
  5. Consume Context: Use useContext in any child component to get the value.
    javascript
import { useContext } from 'react';
function Toolbar() {
  const theme = useContext(ThemeContext); // Gets "dark"
  return <div>The current theme is: {theme}</div>;
}

 


Benefits

  • Avoids Prop Drilling: Eliminates the need to pass props through intermediate components that don't need the data.
  • Simpler Syntax: More concise and declarative than older methods (like render props or Consumer components) for functional components.
  • Global State: Great for sharing data like themes, user info, or language settings across an application. 

Best Practice: Custom Hooks

For cleaner code, especially with complex contexts (like theme + setter), create a custom hook that encapsulates the useContext call and error handling (e.g., checking for null if used outside a provider). 


javascript
// useTheme.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}