webpackreduxwebpack-dev-serverreact-hot-loader

Redux - how to keep the reducer state during hot reload


I use React + Redux + Webpack + WebpackDevserver. Once the hot loader is launched all my reducers are reseted to the initial state.

Can I keep somehow my reducers in the actual state?

My Webpack config contains:

entry: [
    "./index.jsx"
],
output: {
    filename: "./bundle.js"
},
module: {
    loaders: [
        {
            test: /\.js|\.jsx$/,
            exclude: /node_modules/,
            loaders: ["react-hot","babel-loader"],
         }
    ]
},
plugins: [
    new webpack.HotModuleReplacementPlugin()
]

My reducers stats with:

const initialState = {
...
}

export default function config(state = initialState, action) { ...

I start my Webpack Dev-Server just by:

"start": "webpack-dev-server",

Solution

  • Assuming Babel 6, you need to do something along this:

    import {createStore} from 'redux';
    import rootReducer from '../reducers';
    
    export default function configureStore(initialState) {
      const store = createStore(rootReducer, initialState);
    
      if(module.hot) {
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('../reducers', () => {
          const nextReducer = require('../reducers/index').default;
    
          store.replaceReducer(nextReducer);
        });
      }
    
      return store;
    }
    

    You can see the approach in action at my redux demo.