8
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?

More than 1 year has passed since last update.

AGRI SMILEAdvent Calendar 2022

Day 2

[React] export Context するのをやめた話

Last updated at Posted at 2022-11-25

実装A

こういう実装よくあると思うのですが

contexts/hoge.ts
export const HogeContext = React.createContext({}); 
providers/HogeProvider.ts
import { HogeContext } from 'contexts/hoge';

export const HogeProvider: FunctionComponent<{ children: ReactNode }> = ({
  children
}) => {
  const value = ...; // ロジック
  
  return (
    <HogeContext.Provider value={value}>
      {children}
    </HogeContext.Provider>
  );
};
components/Hoge.ts
import { HogeContext } from 'contexts/hoge';

export const Hoge = () => {
  const value = useContext(HogeContext);
  return (
    ...
  );
}

実装追いづらくないですか?

実装B

と言うことで自分は hooks、Provider とまとめて全部詰めちゃいます

libs/Hoge.tsx
// useHoge があれば必要ないので export しない
const HogeContext = React.createContext({});

export const HogeProvider: FunctionComponent<{ children: ReactNode }> = ({
  children
}) => {
  const value = ...; // ロジック
  
  return (
    <HogeContext.Provider value={value}>
      {children}
    </HogeContext.Provider>
  );
};

export const useHoge = () => {
  return useContext(HogeContext);
};

メリット

  • useHoge を利用しているコードから定義元にジャンプした時に実装が見れる
  • HogeProvider を探さなくて済む
  • 各所で HogeContext を import して useContext する手間が少し省ける
8
0
1

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
8
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?