Search code examples
reactjswebpackreduxwebpack-hmr

explicit render with hot module reloading?


I stumbled upon this and couldn't quite understand the rationale behind.

const render = () => {
  const App = require('./app/App').default

  ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('root')
  )
}

render()

if (process.env.NODE_ENV === 'development' && module.hot) {
  module.hot.accept('./app/App', render)
}

The idea of this code supposed to just adding the capability of this React app with Redux, but author also explicitly define render method and having module.hot at the bottom. I don't really have webpack knowledge, wondering if anyone can shed some lights on the usage for the updated code?

The explanation gave by author was

As with the root reducer, we can hot-reload the React component tree whenever a component file changes. The best way is to write a function that imports the component and renders it, call that once on startup to show the React component tree as usual, and then reuse that function any time a component is changed.


Solution

  • Webpack HMR allows you to "swap" a module (file) in your webpack bundle, this provides the best Developer experience, because you don't need to refresh the page in order to see your changes.

    As part of HMR mechanism, the app should "accept" a change and provide a function which will be invoked when the accepted file is changed.

    In your case, you are "accepting" changes in ./app/App which is the root of your app, (it probably the root of the dependency tree), therefore each change in one of the files that are reachable from ./app/App will trigger the function that you have provided (render function). This means that your React app will re-render the Root component when some file is changed.

    Hope this is more clear :]