📙

【React v19】use APIの基本的な使い方 ~コンテクスト編~

2025/02/04に公開

はじめに

こんにちは!
今回はReact v19で新しく追加されたuseAPIのコンテクスト(Context)に関する使い方について紹介しようと思います!
学んだことのアウトプットになりますので、コメントなどいただけますと幸いです!

対象読者

  • useAPIのコンテクストに関する概要・使い方を知りたい方

記事を読むメリット

  • useAPIのコンテクストに関する概要・使い方、メリットを知ることができる

結論

  • useAPIを使うことで useContextのようにコンテクストから値を読み取ることができる
  • ifforなどの条件式の中でも呼び出すことができる

特徴

前提としてuseContextの使い方をまだ学習されていない方は以下を参照してください。
https://ja.react.dev/reference/react/useContext

簡単に説明すると、useContextは親階層から子階層へのpropsのバケツリレーすることなく、グローバルに値を参照することができるReactフックです。

以下のライトモードとダークモードを切り替えるデモコードを例に説明していきます。

デモコード
import { useState, use, createContext } from "react";
import "./styles.css";

// コンテクストの設定
const ThemeContext = createContext({
  theme: "light",
  handleClick: () => {},
});

export default function App() {
  const [theme, setTheme] = useState("light");

  const handleClick = () => {
    setTheme((prevTheme) => {
      return prevTheme === "light" ? "dark" : "light";
    });
  };

  const contextValue = {
    theme,
    handleClick,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      <Section />
    </ThemeContext.Provider>
  );
}

const Section = () => {
  return (
    <Panel title="モード切り替え">
      <p>ボタンを押下するとライトモードとダークモードを切り替えられます</p>
      <Button>モード切り替え</Button>
    </Panel>
  );
};

const Panel = ({ title, children }) => {
  const { theme } = use(ThemeContext);

  return (
    <section className={theme}>
      <h2>{title}</h2>
      <HorizontalRule show={theme === "dark"} />
      {children}
    </section>
  );
};

const Button = ({ children }) => {
  const { handleClick } = use(ThemeContext);

  return <button onClick={handleClick}>{children}</button>;
};

const HorizontalRule = ({ show }) => {
  if (show) {
    const { theme } = use(ThemeContext);
    return <hr className={theme} />;
  }
  return false;
};

コンテクストから値を読み取ることができる

以下のようにuseContextと同様の書き方ができます。

// ...
export default function App() {
  // ...
  return (
    <ThemeContext.Provider value={contextValue}>
      <Section />
    </ThemeContext.Provider>
  );
}
// ...
const Panel = ({ title, children }) => {
  // `useContext`と同様の書き方ができる
  const { theme } = use(ThemeContext);

  return (
    <section className={theme}>
      <h2>{title}</h2>
      {children}
    </section>
  );
};

ifforなどの条件式の中でも呼び出すことができる

以下のようにifforなどの条件式の中でも呼び出すことができます。

// ...
const HorizontalRule = ({ show }) => {
  if (show) {
    const { theme } = use(ThemeContext);
    return <hr className={theme} />;
  }
  return false;
};

まとめ

まとめるとuseAPIは以下のような特徴があります。

  1. useContextのようにコンテクストから値を読み取ることができる
  2. ifforなどの条件式の中でも呼び出すことができる

また、ドキュメントにも記載がありますが、条件式でも使えるという柔軟性からuseContextより優先的に使用するのが良さそうです。

コンテクストが use に渡された場合、useContext と同様に動作します。useContext はコンポーネントのトップレベルで呼び出す必要がありますが、use は if や for などの条件式の中でも呼び出すことができます。use はより柔軟であるため、useContext よりも優先的に使用してください。

参考

https://ja.react.dev/reference/react/use
https://zenn.dev/uhyo/articles/react-use-rfc

Discussion