Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / React

Hot Reloading in Create React App Without Ejecting

0.00/5 (No votes)
15 Jan 2018CPOL 7K  
Hot Reloading in Create React App Without Ejecting

Create React App is great, but the projects it generates don’t have Hot Module Replacement (HMR) set up by default.

But! Create React App projects can support HMR! You just need to add a tiny bit of code to your app.

Here’s what to do:

Add 3 Lines of Code

Here’s the untouched index.js file provided by Create React App:

JavaScript
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";

ReactDOM.render(<App />, document.getElementById("root"));
registerServiceWorker();

At the bottom, add this code:

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

Seriously. That’s it. Have fun hot reloading!

Ready for Prime Time?

This feature is sort of hidden in the current version of Create React App. There are a few open issues regarding hot reloading on Github. Just keep in mind that it may not be 100% perfect, and if anything seems awry, just refresh the page. 👍

Got Redux?

If you’re using Redux in your app, you’ll need to explicitly hot-reload the reducers. You can put this chunk of code wherever you create your store, something like this:

JavaScript
import { createStore } from 'redux';
import rootReducer from '../yourRootReducer';

const store = createStore(rootReducer, /* etc ... */);

// Add this chunk of code:
if (process.env.NODE_ENV !== 'production' && module.hot) {
  // Note! Make sure this path matches your rootReducer import exactly
  // Does not play well with "NODE_PATH" aliasing.
  module.hot.accept('../yourRootReducer', () => {
    const newRootReducer = require('../yourRootReducer').default;
    store.replaceReducer(newRootReducer);
  });
}

Enjoy Fast Refreshes

That’s all there is to it!

Hot Reloading in Create React App Without Ejecting was originally published by Dave Ceddia at Dave Ceddia on January 15, 2018.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)