0
2

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 3 years have passed since last update.

基礎から学ぶReact/React Hooks学習メモ 5-5 useContext

Posted at

React Hooksを基礎から理解する 5-5 useContext

参考
基礎から学ぶReact/React Hooks

useContextとは

  • コンポーネントのさまざまな階層からContextに収容されているデータへのアクセスをすることができる。
  • 親から子、孫へ、propsのいわゆるバケツリレーをしなくても直接値を渡せる。
  • Contextオブジェクト
    • React.createContext()の戻り値
const SampleContextObject = React.createContext();
  • Providerコンポーネント
    • Contextオブジェクトが保持しているコンポーネント
    • 1つのContextで管理できる「コンテキストオブジェクトの値」は1つだけ。
    • ConsumerComponentコンポーネントはProvider内なので、value属性の値を参照できる。
<SampleContextObject.Provider value={ツリー内で共有可能なコンテキストオブジェクトの値} >

  <ConsumerComponent />

</SampleContextObject.Provider>
  • Consumerコンポーネント
    • useContext()を利用することで、Contextから値を取得できるコンポーネント
import React, { useContext } from "react";


const コンテキストオブジェクトの値 = useContext(コンテキストオブジェクト);

useContextの利用例

  • Providerコンポーネントで共有されたデータをConsumerコンポーネントで受け取る
import React, { createContext, useContext } from "react";
import "./styles.css";

// contextオブジェクトの生成
const SampleContextObject = createContext();

const ConsumerComponent = () => {
  // 親コンポーネントからmessageTextを取得
  const messageText = useContext(SampleContextObject);
  console.log(messageText);
  return <p>{messageText}</p>;
};

const message = "I love React!!";

export default function App() {
  // 親コンポーネントに文字列を設定して、Providerでラップする
  return (
    <SampleContextObject.Provider value={message}>
      <ConsumerComponent />
    </SampleContextObject.Provider>
  );
}

Providerコンポーネントからテキストデータを渡してみる

image.png

TextProvider.js
import React, { createContext } from "react";

export const TextContext = createContext();

const text = "これはProviderから渡されたテキストです。";

export const TextProvider = ({ children }) => {
  return <TextContext.Provider value={text}>{children}</TextContext.Provider>;
};
App.js
import { TextProvider } from "./TextProvider";
import { First } from "./First";
import "./styles.css";

export default function App() {
  return (
    <div>
      <TextProvider>
        <First />
      </TextProvider>
    </div>
  );
}
First.js
import { Second } from "./Second";

export const First = () => {
  return (
    <>
      <p>Firstコンポーネント</p>
      <Second />
    </>
  );
};
Second.js
import { Third } from "./Third";

export const Second = () => {
  return (
    <>
      <p>Secondコンポーネント</p>
      <Third />
    </>
  );
};
Third.js
import React, { useContext } from "react";
import { TextContext } from "./TextProvider";

export const Third = () => {
  const textData = useContext(TextContext);

  return (
    <>
      <p>
        Thirdコンポーネント: <b>{textData}</b>
      </p>
    </>
  );
};

useStateを利用したcountデータを渡す

image.png

  • [count, setCount]をProviderのvalueに渡すと、受け取ったコンポーネントから値を変更できる
TextProvider.js
import React, { createContext, useState } from "react";

export const TextContext = createContext();

// const text = "これはProviderから渡されたテキストです。";

export const TextProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  return (
    <TextContext.Provider value={[count, setCount]}>
      {children}
    </TextContext.Provider>
  );
};

  • App.jsは上のApp.jsと同じ
  • First.jsは上のFirst.jsと同じ
  • Second.jsは上のSecond.jsと同じ
  • [count, setCount]を受け取り、値を参照・変更できる
Third.js
import React, { useContext } from "react";
import { TextContext } from "./TextProvider";

export const Third = () => {
  // const textData = useContext(TextContext);
  const [count, setCount] = useContext(TextContext);

  const handleClick = () => {
    setCount((prevCount) => prevCount + 1);
  };

  return (
    <>
      <p>
        Thirdコンポーネント: <b>現在のカウント: {count}</b>
      </p>
      <button onClick={handleClick}>+1ボタン</button>
    </>
  );
};
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?