Logicoya
HOME › オンライン教材 › React超入門 › Lesson 12 useContext
12

useContext

Props ドリリング問題

テーマ切り替え

ページテーマ切り替え機能を実装するには、テーマのステートをコンポーネント間でデータ共有する必要があります。 その手法として useContext があります。

Props ドリリング問題とは

お気に入りの state を App.jsx で管理すると、WorkCard に渡すまでに途中のコンポーネントにも Props を渡す必要があります。

悪い例(プロップスドリル発生)

このプログラムは Props ドリリング で、theme をバケツリレーで渡しています。階層が深くなるほど管理が大変になります。

function App() {
  const theme = 'dark';
  // 1. App から Main へ Props として渡す
  return <Main theme={theme} />; 
}

function Main({ theme }) {
  // 2. Main はテーマを使わないのに、Button に渡すためだけに受け取る(これが無駄)
  return <Button theme={theme} />; 
}

function Button({ theme }) {
  // 3. 孫コンポーネントでようやく使える
  return <button className={`btn-${theme}`}>ボタン</button>;
}

useContext とは

Context API

useContext は React Hooksの1つで、Context APIとも言います。 Props ドリリング を解消して、コンポーネント間でデータを容易に共有・更新できます。

useContext による解決

useContext を使うと、どの階層のコンポーネントからでも直接データを取得できます。

Props と useContext の違い

項目PropsuseContext
データの渡し方親から子へバケツリレーで渡すコンテキスト経由で直接渡す
向いている用途特定の親子間だけのデータアプリ全体で共有したいデータ(ログイン情報やテーマ色など)

3つのステップ

Context API を使うには、大きく分けて3つの手順を踏みます。

ステップ役割使うもの
1. 作成createContextデータの「保管場所」を作る
2. 提供<Context.Provider>データを「使える範囲」を決める
3. 取得useContext必要な場所でデータを「受け取る」

ThemeContext 作成

データを保管するための「空の箱(Context)」を作成します。

コンテキストファイル作成

src に context/ThemeContext.js を作成します。

src/
  └── context/
        └── ThemeContext.js

createContext() でコンテキストを設定します。 初期値は設定しなくても構いません。

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

// 1. Context(保管場所)を作成し、初期値を設定(なくてもOK)
export const ThemeContext = createContext('light');

💡 ここで作った ThemeContext が、データを入れる箱の名前になります。

Provider の利用

ステートと関数定義

theme ステートとテーマ切り替え関数 toggleTheme() を定義します。

/* src/App.jsx */

function App() {
  // テーマステート
  const [theme, setTheme] = useState('light')

  // テーマ切り替え関数
  const toggleTheme = () => {
    setTheme((currentTheme) => (currentTheme === 'light' ? 'dark' : 'light'))
  }

}

ThemeContext インポート

ThemeContext をインポートします。

/* src/App.jsx */
import { ThemeContext } from './ThemeContext';

Provider の設定

<ThemeContext.Provider> で囲むと、その範囲でデータが共有できます。Props には theme、toggleTheme を設定します。

// src/App.jsx

function App() {

  return (
    //  Provider で囲んで、value にデータをセットする
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <div className={styles.app}>
          ...
      </div>
    </ThemeContext.Provider>
  );
}

export default App;

ThemeButton コンポーネント

コンポーネント作成

ThemeButton コンポーネントを作成し、ThemeContext をインポートします。

// src/components/ThemeButton.jsx
import { ThemeContext } from '../context/ThemeContext'

function ThemeButton() {
  return (
    <div></div>
  )
}

export default ThemeButton

コンテキストデータ取得

useContext でコンテキストデータを取得します。

// src/components/ThemeButton.jsx

// useContext インポート
import { useContext } from 'react'
import { ThemeContext } from '../context/ThemeContext'

function ThemeButton() {
  // コンテキストデータを取得
  const { theme, toggleTheme } = useContext(ThemeContext)

  return (
    <div></div>
  )
}

export default ThemeButton

💡このコンポーネントは App から Props を利用せず、useContext でデータを共有できます。

ボタン作成

<button> タグを作成し、クリックで toggleTheme を実行してテーマを切り替えます。 このときダークテーマフラグ isDark、テーマラベル label も定義しておきます。

// src/components/ThemeButton.jsx
import { useContext } from 'react'
import { ThemeContext } from '../context/ThemeContext'
import styles from './ThemeButton.module.css'

function ThemeButton() {
  const { theme, toggleTheme } = useContext(ThemeContext)
  // ダークテーマフラグ
  const isDark = theme === 'dark'
  // テーマラベル
  const label = isDark ? 'Dark Mode' : 'Light Mode'

  return (
    <button
      type="button"
      className={styles.button}
      onClick={toggleTheme}
      aria-pressed={isDark}
      aria-label={`Switch theme. Current theme: ${label}`}
      title="テーマを切り替え"
    >
      <span className={styles.dot} aria-hidden="true" />
      <span>{label}</span>
    </button>
  )
}

export default ThemeButton
/* src/components/ThemeButton.module.css */
.button {
  display: inline-flex;
  align-items: center;
  gap: 0.55rem;
  padding: 0.35rem 0.875rem;
  border: 1px solid #d1d5db;
  border-radius: 999px;
  background: white;
  color: #374151;
  font-size: 0.875rem;
  font-weight: 500;
  line-height: 1;
  cursor: default;
  white-space: nowrap;
}

.dot {
  width: 0.55rem;
  height: 0.55rem;
  border-radius: 999px;
  background: #111827;
  box-shadow: 0 0 0 3px #e5e7eb;
}

テーマボタン追加

Header コンポーネント修正

Header コンポーネントに ThemeButton を追加します。

/* src/components/Header.jsx */
import styles from './Header.module.css'
import logo from '../assets/logo.svg'
// インポート
import ThemeButton from './ThemeButton'

function Header() {
    return (
        <header className={styles.header}>
            <div className={styles.logo}>
                <img src={logo} alt="Logo" />
            </div>
            <div className={styles.title}>Anime Station</div>
            <div className={styles.actions}>
                <ThemeButton />
            </div>
        </header>
    )
}

export default Header

Header.module.css に .actions を追加します。

/* src/components/Header.module.css */

/* 追加 */
.actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 0.75rem;
    flex-wrap: wrap;
    margin-left: auto;
}

動作確認

ラベルが変更するか確認します。

ライト

ダーク

テーマ変更

theme ステート

メインタグの data-theme に theme ステートを設定します。

/* src/App.jsx */
function App() {

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {/* data-theme={theme} を追加 */}
      <div className={styles.app} data-theme={theme}>

      </div>
    </ThemeContext.Provider>
  )
}

export default App

ダークテーマ追加

各 CSS Module にダークテーマ data-theme='dark' のスタイルを追加します。

/* src/App.module.css */
.app {
  --app-bg: #f9fafb;
  --surface: #ffffff;
  --surface-muted: #f3f4f6;
  --border: #e5e7eb;
  --border-strong: #d1d5db;
  --text: #111827;
  --text-muted: #374151;
  --text-soft: #6b7280;
  --text-faint: #9ca3af;
  --accent: #1f2937;
  --accent-contrast: #ffffff;
  --shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.08);
  min-height: 100vh;
  background: var(--app-bg);
  color: var(--text);
  display: flex;
  flex-direction: column;
  transition: background-color 0.2s ease, color 0.2s ease;
}

.main {
  flex: 1;
  padding: 0rem 1.5rem;
  max-width: 960px;
  margin: 0 auto;
  width: 100%;
}

.sectionTitle {
  color: var(--text);
  font-size: 1.25rem;
  font-weight: bold;
  margin-bottom: 1.5rem;
  padding-left: 0.75rem;
  border-left: 4px solid var(--accent);
  text-align: left;
}

.error {
  text-align: center;
  color: #e11d48;
  padding: 3rem 0;
}

/* Dark theme */
.app[data-theme='dark'] {
  --app-bg: #0f172a;
  --surface: #111827;
  --surface-muted: #1f2937;
  --border: #334155;
  --border-strong: #475569;
  --text: #f8fafc;
  --text-muted: #cbd5e1;
  --text-soft: #ffffff;
  --text-faint: #ffffff;
  --accent: #e2e8f0;
  --accent-contrast: #0f172a;
  --shadow-hover: 0 10px 24px rgba(2, 6, 23, 0.35);
}
/* src/components/Footer.module.css */
.footer {
    background: var(--surface);
    color: var(--text-muted);
    text-align: center;
    padding: 1.5rem;
    font-size: 0.875rem;
    margin-top: 3rem;
    border-top: 1px solid var(--border);
}
/* src/components/SearchBar.module.css */
.searchBar {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 1.25rem;
  padding: 1rem;
}
.section {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.sectionTitle {
  font-size: 0.95rem;
  font-weight: 600;
  color: #374151;
  margin: 0;
}
.input {
  padding: 0.6rem 1rem;
  border: 1px solid var(--border);
  background: var(--surface);
  color: var(--text);
  border-radius: 8px;
  font-size: 0.95rem;
  outline: none;
}
.input:focus {
  color: var(--text-muted);
}
.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}
.filter {
  padding: 0.35rem 1rem;
  border: 1px solid var(--border);
  border-radius: 999px;
  background: var(--surface);
  color: var(--text);
  font-size: 0.875rem;
  cursor: pointer;
}
.filter:hover {
  background: var(--surface-muted);
}
.filterActive {
  padding: 0.35rem 1rem;
  border: 1px solid var(--accent);
  border-radius: 999px;
  background: var(--accent);
  color: var(--accent-contrast);
  font-size: 0.875rem;
  cursor: pointer;
}

Header 修正

useContext で theme を取得して、svg をテーマで切り替えます。

/* src/components/Header.jsx */
import styles from './Header.module.css'
import logo from '../assets/logo.svg'
import logoDark from '../assets/logo-dark.svg'
import ThemeButton from './ThemeButton'
import { ThemeContext } from '../context/ThemeContext'
import { useContext } from 'react'

function Header() {
    const { theme } = useContext(ThemeContext)

    return (
        <header className={styles.header}>
            <div className={styles.logo}>
                <img src={theme === 'dark' ? logoDark : logo} alt="Logo" />
            </div>
            <div className={styles.title}>Anime Station</div>
            <div className={styles.actions}>
                <ThemeButton />
            </div>
        </header>
    )
}

export default Header

動作確認

ライトテーマ、ダークテーマの切り替えを確認します。

まとめ

ポイント内容
Props ドリリング中間コンポーネントに不要な Props を渡し続ける問題
createContextContext オブジェクトを作成する
Providervalue で指定した値を子孫コンポーネントに提供する
useContextProvider から値を取得する
childrenコンポーネントの子要素を受け取る特別な Props
カスタムHookuseContext をラップしてシンプルに呼び出せるようにする
ファイル分離Context・Provider・Hook を別ファイルにしてESLint警告を回避
使い分けシンプルな親子間は Props・複数階層またぐなら Context