Переменная (пропс), которая будет доступна в любом дочернем компоненте (Контекст)

Когда один и тотже параметр (пропс) используется дочерними компонентами, то данный пропс дублируется каждым компонентом.

// components/ButtonGroup.js
import Button from './Button';

export default function ButtonGroup({theme}) {
  return <div>
    <Button theme={theme}>Кнопка 1</Button>
    <Button theme={theme}>Кнопка 2</Button>
    <Button theme={theme}>Кнопка 3</Button>
  </div>
}

Через контекст (англ. context) можно указать, что указанный пропс будет доступен в любом дочернем компоненте.

Для начала надо создать контекст:

// context/ThemeContext.js
import { createContext } from 'react';

export const ThemeContext = createContext('light');

Теперь данный контекст можно использовать в компоненте:

// components/ButtonGroup.js
import { Button } from './Button';
import { ThemeContext } from '../contexts/ThemeContext';

export function ButtonGroup({theme}) {
  return <div>
    <ThemeContext.Provider value={theme}>
      <Button>Кнопка 1</Button>
      <Button>Кнопка 2</Button>
      <Button>Кнопка 3</Button>
    </ThemeContext.Provider>
  </div>
}

Стоит обратить внимание, что теперь для каждого компонента <Button> не указывается пропс «theme».

В дочерних компонентах обратиться к <ThemeContext> можно через следующий код:

// components/Button.js
import { useContext } from 'react';
import { ThemeContext } from '../contexts/ThemeContext';

export function Button({children}) {
  const theme = useContext(ThemeContext);

  return <button className={theme}>{children}</button>
}

Пример кода на Playcode