LoginSignup
0
0

More than 1 year has passed since last update.

【React + Typescript】useContextで子コンポーネントに値を渡す

Last updated at Posted at 2022-09-23

全ページに共通して使用している親コンポーネントにて実行した処理結果を、
子コンポーネントに渡す必要があったため、useContextを使うことにしました。

処理としては、カスタムフックを使用して生成されたインスタンスを子に渡します。

parent.tsx(親コンポーネント)
import React, { createContext, useState } from 'react';
import { useCreateInstance } from '@/hooks/api/useCreateInstance';

type InstanceType = Record<string, any>;
export const Instance = createContext<InstanceType>({});

const ParentComponent: React.FC = () => {
  const instance = useCreateInstance();

  return (
    <>
      <Instance.Provider value={instance}>
        <ChildComponent />
      </Instance.Provider>
    </>
  )
}
child.tsx(子コンポーネント)
import React, { useContext } from 'react';
import { PayjpInstance } from '@/pages/parent.tsx';

const ChildComponent: React.FC = () => {
  const instance = useContext(instance);
  // ここから下でinstanceが使用できる

  return (
    <>
      {/*割愛*/}
    </>
  )
}

propsを使わずとも一気に下層の子コンポーネントまで値を簡単に渡すことができて感動しました。

参考記事

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