#atom

Subtitle:

React Hook for consuming context to access data without prop drilling


Core Idea:

useContext is a React Hook that subscribes a component to a context object, allowing it to read and react to context changes without receiving props from parent components.


Key Principles:

  1. Context Subscription:
    • Components can subscribe to context values created with createContext.
  2. Tree-Based Propagation:
    • Context is passed down the component tree from providers to consumers.
  3. Dynamic Updates:
    • Changes to context value automatically trigger re-renders of subscribed components.

Why It Matters:


How to Implement:

  1. Create Context:
    • Define context with createContext(defaultValue).
  2. Provide Context:
    • Wrap components in <Context.Provider value={someValue}>.
  3. Consume Context:
    • Use useContext(Context) hook in any component within provider.

Example:

import { createContext, useContext, useState } from 'react';

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

function App() {
  const [theme, setTheme] = useState('light');
  
  return (
    <ThemeContext.Provider value={theme}>
      <Panel />
      <Button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
        Toggle Theme
      </Button>
    </ThemeContext.Provider>
  );
}

function Panel() {
  const theme = useContext(ThemeContext);
  const className = 'panel-' + theme;
  
  return (
    <div className={className}>
      <h1>Current theme: {theme}</h1>
    </div>
  );
}

Connections:


References:

  1. Primary Source:
    • React Documentation on useContext Hook
  2. Additional Resources:
    • "Advanced React Patterns" articles on effective context usage
    • React DevTools for debugging context providers and values

Tags:

#react #hooks #context #state-management #component-communication


Connections:


Sources: