Skip to content

Instantly share code, notes, and snippets.

@sapegin
Created November 28, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sapegin/713a2f4b6a9fe3ceedd16a913a684c0b to your computer and use it in GitHub Desktop.
Save sapegin/713a2f4b6a9fe3ceedd16a913a684c0b to your computer and use it in GitHub Desktop.

Hot module replacement in React and webpack

The simplest way to enable HMR:

import React from 'react';
import ReactDOM from 'react-dom';

function render() {
  ReactDOM.render(
    <h1>Hello, webpack-blocks!</h1>,
    document.getElementById('root')
  );
}

render();

if (module.hot) {
  module.hot.accept(render);
}

This will refresh the whole file, that may be a problem if you create a Redux store here — it will be recreated on every refresh, and Redux will complain:

does not support changing store on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.

To fix that you need to make store creation a singleton:

if (String(process.env.NODE_ENV) === 'production') {
    module.exports = require('./configureStore.production.js').default();
} else {
    module.exports = require('./configureStore.development.js').default();
}

You can also reload the root component instead of an index.js, which may be a good idea if you import polyfills and other static things there:

import React from 'react';
import ReactDOM from 'react-dom';
import Root from './containers/Root';

const container = document.getElementById('app');
ReactDOM.render(<Root />, container);

if (module.hot) {
    module.hot.accept(['./containers/Root'], () => {
        const NextRoot = require('./containers/Root').default;
        ReactDOM.render(<NextRoot />, container);
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment