0
0
Reactframework~5 mins

Consuming context in React

Choose your learning style9 modes available
Introduction

Context lets components share data without passing props step-by-step. Consuming context means using that shared data inside a component.

You want to share user login info across many parts of your app.
You need a theme color available in many components without passing it down manually.
You want to access language settings anywhere in your app easily.
You want to avoid 'prop drilling' where props are passed through many layers.
You want components to react to shared state changes automatically.
Syntax
React
const value = useContext(MyContext);
useContext is a React hook to read the current context value.
You must import useContext from 'react' and have a Context created with React.createContext.
Examples
This reads the context value and shows it inside a div.
React
import React, { useContext } from 'react';
const MyContext = React.createContext('default');

function MyComponent() {
  const value = useContext(MyContext);
  return <div>{value}</div>;
}
This uses the theme from context to set a CSS class on a button.
React
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Click me</button>;
}
Sample Program

This example creates a UserContext with default 'Guest'. The App component provides 'Alice' as the user. The Greeting component consumes the context and shows "Hello, Alice!".

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

const UserContext = createContext('Guest');

function Greeting() {
  const user = useContext(UserContext);
  return <h1>Hello, {user}!</h1>;
}

export default function App() {
  return (
    <UserContext.Provider value="Alice">
      <Greeting />
    </UserContext.Provider>
  );
}
OutputSuccess
Important Notes

Context only works if the component is inside a matching Provider.

When the Provider value changes, all consuming components update automatically.

Don't overuse context for everything; use it for global or shared data.

Summary

Consuming context means reading shared data inside a component using useContext.

It helps avoid passing props through many layers.

Always wrap consuming components inside a Provider to supply the context value.