LoginSignup
7
3

More than 3 years have passed since last update.

React ContextのdefaultValueのちょっとかしこい(かもしれない)使い方

Last updated at Posted at 2019-05-10

はじめに

React Context APIはReact.useContextにより格段に使いやくなりました。ところで、React.createContextにはdefaultValueを指定します。ここに何を指定すればよいでしょうか?しばしば null を指定している例を見ます。

よくある例

import { createContext, useContext } from 'React';
const MyContext = createContext(null);
export const MyProvider = MyContext.Provider;
export const useMyValueFoo = () => {
  const value = useContext(MyContext);
  if (!value) {
    throw new Error('You probably forgot to put <MyProvider>.');
  }
  return value.foo;
};

contextの値にオブジェクトを期待する場合は、ちゃんとProviderで値が設定されているか、つまりdefaultValueのnullのままになっていないかチェックして開発者向けにエラーを表示するテクニックです。

提案

形が決まっているオブジェクト限定ですが、defaultValueにエラーを表示するオブジェクトを指定しておいてはどうでしょうか。上記の例が次のようなコードになります。

import { createContext, useContext } from 'React';
const warningObject = {
  get foo() {
    throw new Error('You probably forgot to put <MyProvider>.');
  },
};
const MyContext = createContext(warningObject);
export const MyProvider = MyContext.Provider;
export const useMyValueFoo = () => {
  const value = useContext(MyContext);
  return value.foo;
};

カスタムフックの実装からboilerplateが減ってスッキリしたと思いませんか。

おわりに

自分がライブラリを実装しているときに思いついた方法なのですが、まだあまり他では見たことはありません。ぜひ試してみてください。一つの難点は、この方法は型定義とは少し相性が良くないかもしれません。

7
3
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
7
3