問題一覧に戻る
上級useReducer
問題79: Contextとの組み合わせ
グローバル状態管理のためにContext APIとuseReducerを組み合わせる方法を学びます。このReduxライクなパターンは、すべてのコンポーネントに集中化された状態とdispatch関数を提供します。Providerがアプリをラップし、どのコンポーネントもcontextを通じて状態にアクセスできます。中規模アプリケーションでは外部状態管理ライブラリの優れた代替手段です。
import React, { createContext, useContext, useReducer } from 'react';
{/* ストアcontextを作成 */}
const StoreContext = ();
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT': return { count: state.count + 1 };
case 'DECREMENT': return { count: state.count - 1 };
default: return state;
}
}
{/* ストアProviderコンポーネント */}
function StoreProvider({ }) {
const [state, dispatch] = (reducer, { count: 0 });
return (
<StoreContext.Provider value={{ , }}>
{children}
</StoreContext.Provider>
);
}
function Counter() {
{/* contextからストアを使用 */}
const { state, dispatch } = (StoreContext);
return (
<div>
<p>{state.count}</p>
<button onClick={() => ({ type: 'INCREMENT' })}>+</button>
</div>
);
}
function App() {
return (
< >
<Counter />
</ >
);
}
export default App;