This is my first article in Hashnode. In this article, I'm trying to explain what hot reloading is and how you can add it to your react project. In this article, we are going to use Webpack module bundler and excellent react-hot-reloader 3 plugin by Dan Abramov to do hot reloading.
What is Hot Reloading?
If you are new to React land, you must have of heard of a lot of buzz words. One of them is Hot Reloading. Hot-reloading is built atop Webpack's HMR feature. Webpack's HMR(Hot Module Replacement) feature injects the new version of a file that you edited in runtime. This way you don't have to restart the server every time you modify a file. You may think, why do we need react-hot-reloader plugin provided the Webpack's HMR does the job. With only Webpack's HMR, the internal state of react application is lost. That's where react-hot-reloader comes in. Now, in addition to injecting new changes in runtime, your react applications internal state is also maintained.
Why Hot Reloading?
It saves a lot of development time by injecting changes in runtime. Restarting the server whenever you make a change like old time is not a good idea. Since, with modern dev tools like babel and other things in your stack, a medium sized project takes more than 5 seconds to restart. This 5 seconds every time you make a change adds up to a lot of time wastage. Adding hot reloading to your project increases your developer experience ten folds.
Steps to add hot reloading
- Install beta version of react hot reloader 3
npm i react-hot-loader@3.0.0-beta.2
- Edit your webpack configuration and add these lines
entry: [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './app/main' // Your app's main entry point ], ... plugins: [ new webpack.HotModuleReplacementPlugin() ],
- Edit your .babelrc configuration and add this line below presets
"plugins": ["react-hot-loader/babel"]
Now edit your app/main.js which you have mentioned in the webpack config and add these lines
import { AppContainer } from 'react-hot-loader'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; // Your root component ... const mountApp = document.getElementById('root'); ReactDOM.render( <AppContainer> <App /> </AppContainer>, mountApp ); if (module.hot) { const nextApp = require('./App').default; module.hot.accept('./App', () => { ReactDOM.render( <AppContainer> <nextApp /> </AppContainer>, mountApp ); }); }
That's is all you need to get hot reloading working in your application.