Course contentsShow
← React
Lesson 799 of 2,39621. Context FundamentalsFree lesson

useContext Hook Syntax

Learn how to consume context values with useContext(MyContext) and access data provided by ancestors.

useContext Hook Syntax

What you'll learn: How to consume context values with the useContext hook to access data provided by ancestor components.


Why We Need useContext

You've learned how to create contexts and set up providers. Now you need a clean, modern way to consume those values in your components. The useContext hook is React's current recommended approach—it's cleaner and more readable than the legacy Context.Consumer pattern.

The Basic Syntax

The useContext hook takes one argument: the context object you created with createContext. It returns whatever value is currently provided by the nearest matching Provider above it in the tree.

import { useContext } from 'react';
import { MyContext } from './MyContext';

function MyComponent() {
  const value = useContext(MyContext);
  // Now you can use `value` directly
}

The Pattern in Action

// ThemeContext.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');

// App.js
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// Toolbar.js
function Toolbar() {
  const theme = useContext(ThemeContext);
  // theme is "dark" here
  return <div className={theme}>Toolbar</div>;
}

Key Rules

  • Pass the context object itself, not a string or the Provider
  • The hook reads from the nearest Provider ancestor
  • If no Provider exists above, it uses the default value from createContext
  • Components using useContext re-render when the Provider's value changes

Key Takeaway: useContext(MyContext) gives you direct access to the context value from the nearest Provider, eliminating prop drilling with a simple, readable hook call.