0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React19になってContext APIはどう変わったか?

Posted at

ReactにおけるContext APIとは何か

ReactにContext APIは、アプリ全体で簡単にデータを共有するための仕組みです。

例えば、ユーザー名やテーマ(明るい・暗い)などの情報を、色々なコンポーネントで使いたい時、普通は親から子へpropsで渡します。

でも、データを深い階層に渡したいとき、いちいち中間のコンポーネントにもpropsを渡す必要がありこれがとても面倒です。

Context APIを使用すると、この面倒なprops渡しをしなくてもデータをどこからでも直接使えるようになります。

React18までのContext API

・createContextでコンテキストを生成し、Providerで値を提供、useContextで値を使用する。

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

const ThemeContext = createContext();

const App = () => {
  return (
    <ThemeContext.Provider value={{ theme: 'dark' }}>
      <ChildComponent />
    </ThemeContext.Provider>
  );
};

const ChildComponent = () => {
  const { theme } = useContext(ThemeContext);
  return <p>現在のテーマ: {theme}</p>;
};

export default App;

・基本的な機能はシンプルでわかりやすいが、大規模なアプリではパフォーマンスの問題が発生する場合も

・Contextの値が変更されると、Provider以下の全てのコンポーネントが再レンダリングされる可能性があるため、パフォーマンスの最適化が必要です。

・DevToolsでContextの値を確認することはできますが、変更の流れや詳細なトラッキングは制限されています。

React19のContext API

・タグの導入
React19では、の代わりに<Context>タグを直接使用可能になり、記述が簡潔になりました。

import React, { createContext, use } from 'react';

const ThemeContext = createContext();

const App = () => {
  return (
    <ThemeContext value={{ theme: 'dark' }}>
      <ChildComponent />
    </ThemeContext>
  );
};

const ChildComponent = () => {
  const { theme } = use(ThemeContext);
  return <p>現在のテーマ: {theme}</p>;
};

export default App;

・デバッグツールの向上
DevToolsで特定のContextに設定されている「値」が変更された履歴を確認できるようになりました。値がどのように変更されたのかを時系列で追跡できるため、予期しないデータの変更やバグの原因を特定しやすくなります。

使い方
①DevToolsの「Components」タブを開く
②Contextの値を確認する
③変更履歴を追跡する

・再レンダリングの原因が明確になった
Context APIでは、値の変更が原因でコンポーネントが再レンダリングされることがあります。React 19では、どのContextの値が原因で再レンダリングが発生したのかを明確に確認できるようになりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?