React.createContext point of defaultValue? Ask Question

React.createContext point of defaultValue? Ask Question

On the React 16 Context doc page, they have examples that look similar to this one:

const defaultValue = 'light'
const SomeContext = React.createContext(defaultValue)

const startingValue = 'light'
const App = () => (
  <SomeContext.Provider theme={startingValue}>
    Content
  </SomeContext.Provider>
)

defaultValueを他の値に設定するかstartingValue、設定しない場合 ( )、 が上書きされるため、 は役に立たないようですundefined。 問題ありません。そのように動作するはずです。

しかし、それでは の意味は何でしょうかdefaultValue?

変化しない静的コンテキストが必要な場合は、以下のようにして、プロバイダをdefaultValue

const App = () => (
  <SomeContext.Provider>
    Content
  </SomeContext.Provider>
)

ベストアンサー1

プロバイダーがない場合、defaultValue引数は関数に使用されますcreateContext。これは、コンポーネントをラップせずに単独でテストする場合や、プロバイダーとは異なる値でテストする場合に役立ちます。


コードサンプル:

import { createContext, useContext } from "react";

const Context = createContext( "Default Value" );

function Child() {
  const context = useContext(Context);
  return <h2>Child1: {context}</h2>;
}

function Child2() {
  const context = useContext(Context);
  return <h2>Child2: {context}</h2>;
}

function App() {

  return (
    <>
      <Context.Provider value={ "Initial Value" }>
        <Child /> {/* Child inside Provider will get "Initial Value" */}
      </Context.Provider>
        <Child2 /> {/* Child outside Provider will get "Default Value" */}
    </>
  );
}

Codesandbox デモ

おすすめ記事