目次
- はじめに
- Next.js と Redux の概要
- 環境構築
- Redux ストアの作成
- Next.js に Redux を統合する
- 非同期アクションの対応
- Redux DevTools のセットアップ
- 最適化Tips
- さいごに
1. はじめに
この記事では、Next.js を使ったアプリケーションで Redux を用いた状態管理方法と、パフォーマンスの最適化手法について解説していきます。独自のリアクティブなストアを実装せずにすむ Redux を効果的に導入し、アプリのパフォーマンスを向上させましょう。
2. Next.js と Redux の概要
3. 環境構築
Next.js と Redux の環境構築が完了していることを前提に進めます。まだの場合は、以下の手順でセットアップしてください。
# Next.js アプリケーションの作成 npx create-next-app my-next-redux-app cd my-next-redux-app # Redux のインストール npm install redux react-redux
4. Redux ストアの作成
store.js
:
import { createStore } from 'redux' const initialState = { count: 0, } const rootReducer = (state = initialState, action) => { switch (action.type) { case 'INCREMENT': return { ...state, count: state.count + 1 } default: return state } } export const store = createStore(rootReducer)
5. Next.js に Redux を統合する
_app.js
:
import React from 'react' import { Provider } from 'react-redux' import { store } from '../store' import '../styles/globals.css' const MyApp = ({ Component, pageProps }) => { return ( <Provider store={store}> <Component {...pageProps} /> </Provider> ) } export default MyApp
6. 非同期アクションの対応
thunks.js
:
import { createStore, applyMiddleware, compose } from 'redux' import thunk from 'redux-thunk' // Redux Store の作成 export const store = createStore(rootReducer, applyMiddleware(thunk))
7. Redux DevTools のセットアップ
store.js
:
import { createStore, applyMiddleware, compose } from 'redux' import thunk from 'redux-thunk' const composeEnhancers = typeof window !== 'undefined' ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose const store = createStore( rootReducer, composeEnhancers(applyMiddleware(thunk)) ) export default store
8. 最適化Tips
9. さいごに
この記事では、Next.js と Redux を組み合わせた状態管理方法と最適化について解説しました。より効率的な状態管理を目指して、アプリケーションの品質を向上させましょう。