0
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.

React Contextでグローバルなstate管理

Posted at

目的

Reactを自己学習しています。自分の備忘録として書きます。誤りがあればご指摘をお願いします。

グローバルなState管理とは

複数のコンポーネントで共有される状態(state)を一箇所で管理するための仕組み。Reactにおいて、状態(state)は、そのコンポーネント内で管理されるが、複数のコンポーネントで共有する必要がある場合に、グローバルな状態としてどこらでも参照できるように管理する必要がある。

Context APIを使ったグローバルなstate管理の方法

①createContextメソッドの使用
②Providerコンポーネントで参照先に渡す値を指定
③useContextフックを使ってオブジェクトにアクセス

①createContextメソッドの使用

createContextメソッドを使って、状態共有のための新しいContextオブジェクトを作成する。

UserProvider.jsx
export const UserContext = createContext({});

//UserContextは、状態の共有に使用されるコンテキスト
//デフォルトでは空のオブジェクトであるが、UserProviderを使用して任意の値を設定できる

②Providerコンポーネントで参照先に渡す値を指定

return (
        < 作成したContextオブジェクト.Provider value={{ 渡したい値(グローバルなstate)}}>
            <参照先 />
        </作成したContextオブジェクト.Provider>
    );

作成されたContextオブジェクトが持っているProviderコンポーネントで参照先のコンポーネントもしくはchildrenをラップする。

UserProvider.jsx
export const UserProvider = (props) => {//UserContextはProviderとConsumerコンポーネントを所持している
    const { children } = props;
    const [userInfo, setUserInfo] = useState(null);
    return (
        <UserContext.Provider value={{ userInfo, setUserInfo }}>
            {children}
        </UserContext.Provider>
    );
};
    
    //childrenプロパティでラップされていない場合、UserContextにuserInfoとsetUserInfoを設定することができない
    //つまり子要素のコンポーネントに渡すことができなくなる

③useContextフックを使ってオブジェクトにアクセス

useContextフックを使って、作成Contextオブジェクトにアクセスする。

UserIcon.jsx
const { グローバルなstate  } = useContext(作成したContextオブジェクト);
UserIcon.jsx
export const UserIconWithName = memo((props) => { //ユーザーのアイコンと名前のセット
    console.log(`UserIconWithName`);
    const { image, name } = props;
    const { userInfo } = useContext(UserContext);
    console.log(userInfo);//isAdminプロパティを確認
    const isAdmin = userInfo ? userInfo.isAdmin : false;
    return (
        <SContainer>
            <SImg height={160} width={160}
            src={image}
            alt={name}/>
            <SName>{name}</SName> 
            {isAdmin && <SEdit>編集</SEdit>}{/*//isAdminがtrueなら編集リンク表示 */}
        </SContainer>
    );
});

これでUserProvider.jsxからUserIcon.jsxへ直接グローバルなstateを渡すことができました。グローバルなstate管理の方法として他にもRedux、Recoilなどもあるので後程まとめていこうと思います。

参考記事
【React】グローバルなstate管理について学ぶ Context

Udemy Reactに入門した人のためのもっとReactが楽しくなるステップアップコース完全版

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?