LoginSignup
27
20

More than 3 years have passed since last update.

【React Hooks】グローバル状態管理にはContextAPIを使おう

Last updated at Posted at 2020-03-31

Reactでグローバルな状態管理といえばReduxですが、Context APIを使えば似たようなことができるので紹介します。

まずは、グローバル状態を定義します。

Global.js
import React, { useState } from 'react';

export const GlobalContext = React.createContext({});

export const GlobalProvider = ({
    children
}) => {
    const [someState, setSomeState] = useState(null);
    const [someState2, setSomeState2] = useState(null);

    return (
        <GlobalContext.Provider
            value={{
                someState,
                setSomeState,
                someState2,
                setSomeState2
            }}
        >
            {children}
        </GlobalContext.Provider>
    );
};

ここではGlobalContextGlobalProviderの二つをexportします。

次に、アプリケーションのルートにあたるファイル(./src/index.jsまたは./src/App.js)内でGlobalProviderを読み込ませます。

index.js
import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';
import { GlobalProvider } from '@/contexts/Global';

ReactDOM.render((
    <GlobalProvider>
        <App />
    </GlobalProvider>
), document.getElementById('root'));

あとは、コンポーネント内でGlobalContextを読み込めば、グローバル状態を参照、更新できるようになります。

Page.js
import React, { useEffect, useContext } from 'react';
import { GlobalContext } from '@/contexts/Global';

export default () => {
    const { someState, setSomeState } = useContext(GlobalContext);

    useEffect(() => {
        // handler
    }, [someState]);

    return (
        <div>
            {someState}
        </div>
    );
};

Reduxよりもお手軽にグローバルな状態管理ができるようになりました。
個人的にはフローがややこしいReduxよりもこちらの方が便利だと思いました。

27
20
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
27
20