Hot Modules In Create React App

Create React App automatically reloads css style changes but not other code changes.

Adding hot modules to a create-react-app lets you change source code in your app and see the changes without the app reloading.

Below the ReactDOM.render function in src/index.js add the following snippet:

if (module.hot) {
  module.hot.accept("./App", () => {
    const NextApp = require("./App").default;
    ReactDOM.render(
      <NextApp/>,
      document.getElementById('root')
    );
  });
}

That’s it.

Go to your browser, update some source code and the changes will appear immediately.

Unfortunately, your app will lose internal state with any changes. I haven’t figured out a way to maintain state without ejecting or rewiring the app. To rewire you app checkout Dave Ceddia’s article on the topic.

If you want follow the approach above but you have a component in the index file (like a Routes component) then you can swap out the path name with a component like so.

if (module.hot) {
  module.hot.accept(Routes, () => {
    const NextApp = Routes.default;
    ReactDOM.render(
        <NextApp /> ,
      document.getElementById('root')
    );
  });
}
 
1
Kudos
 
1
Kudos

Now read this

React setState takes an updater function

If you increment a count in state using a state update function 3 times then the final count will be 3. state = {count: 0} this.setState( previousState => ({count: previousState.count++})) this.setState( previousState => ({count:... Continue →