← React Beginner Questions - Set 3 Q23

What is the purpose of context in React?

React Beginner Questions - Set 3

Context removes prop drilling: a value is published once and read anywhere below, without passing it through every intermediate component.

Example

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

const ThemeContext = createContext('light');

function Toolbar() {
  const theme = useContext(ThemeContext);   // no props involved
  return <button className={theme}>Save</button>;
}

export default function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={theme}>
      <Toolbar />
      <button onClick={() => setTheme(t => (t === 'light' ? 'dark' : 'light'))}>
        Toggle theme
      </button>
    </ThemeContext.Provider>
  );
}

What to notice

← Back to the question list