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

Today I Learnt Some HTML.

Total Days 2 Total Earned $0. I learnt that a “tag” is a bit of code that tell a browser what to do. For a tag to work you have to <open> it and then </close> it. If you want some text on a webpage you put it inside a... Continue →