Skip to main content

Accessing context in a component

Option 1. Modern - via the useContext hook (function components)

This is the main and most convenient way in React with hooks.

javascript
import { useContext } from "react"; import { ThemeContext } from "./ThemeContext"; function Button() { const theme = useContext(ThemeContext); // get the current context value return <button className={theme}>Theme: {theme}</button>; }

What useContext(Context) does:

  • returns the value passed to the nearest <Context.Provider>;
  • automatically subscribes the component to updates of that value;
  • triggers a re-render if the Provider's value changes.

Option 2. Older - via <Context.Consumer>

Used in class components or where hooks are unavailable.

javascript
import { ThemeContext } from "./ThemeContext"; function Button() { return ( <ThemeContext.Consumer> {theme => <button className={theme}>Theme: {theme}</button>} </ThemeContext.Consumer> ); }

Works the same way as useContext, but the syntax is bulky - it is used rarely, mostly for backward compatibility.


Option 3. In a class component via contextType

If you are using a class component (without hooks):

javascript
import React from "react"; import { ThemeContext } from "./ThemeContext"; class Button extends React.Component { static contextType = ThemeContext; render() { const theme = this.context; // access to the context return <button className={theme}>Theme: {theme}</button>; } }

Features:

  • works with only one context;
  • React automatically substitutes the value from the nearest <Provider>.

A full-cycle example

javascript
// ThemeContext.js import { createContext } from "react"; export const ThemeContext = createContext("light"); // App.jsx import { ThemeContext } from "./ThemeContext"; import Button from "./Button"; export default function App() { return ( <ThemeContext.Provider value="dark"> <Button /> </ThemeContext.Provider> ); } // Button.jsx import { useContext } from "react"; import { ThemeContext } from "./ThemeContext"; export default function Button() { const theme = useContext(ThemeContext); return <button className={theme}>Current theme: {theme}</button>; }

As a result: the Button component gets access to "dark" directly, without passing props through the tree.


Summary

ApproachWhere to useHow
useContext(Context)Modern, function componentsconst value = useContext(MyContext)
<Context.Consumer>Universal, older syntax<Context.Consumer>{value => (...)}</Context.Consumer>
contextTypeClass componentsstatic contextType = MyContext + this.context

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.