Blog>
Snippets

Hot Module Replacement (HMR)

Provide an example of configuring Hot Module Replacement to reflect changes in real time without refreshing the entire page, improving the developer experience.
if (module.hot) {
    module.hot.accept('./file-to-watch.js', function() {
        // Callback function to run when 'file-to-watch.js' changes
        updateSomeModule();
    });
}
This piece of code is placed inside a JavaScript module to set up HMR for a specific file called 'file-to-watch.js'. When this file changes, the callback function `updateSomeModule` will be called.
function updateSomeModule() {
    // Logic to update the module without a full page reload
    // Example: Re-render a component with the updated code
    const UpdatedComponent = require('./file-to-watch.js').default;
    // Assume we have a method to re-render the component
    renderComponent(UpdatedComponent);
}
The `updateSomeModule` function re-renders the component with the updated module. It replaces the old module with the new one without refreshing the whole page. This function must be written by the developer to handle the specific update logic required by their application.