Skip to content

Instantly share code, notes, and snippets.

@remy
Created June 1, 2017 12:27
Show Gist options
  • Save remy/b0b25036b2254d200917e976fdc3eed0 to your computer and use it in GitHub Desktop.
Save remy/b0b25036b2254d200917e976fdc3eed0 to your computer and use it in GitHub Desktop.
A take on HMR. I don't remember exactly where it came from, but it works for me.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
const rootEl = document.getElementById('root');
// Create a reusable render method that we can call more than once
let render = () => {
// Dynamically import our main App component, and render it
const App = require('./containers/App').default;
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootEl
);
};
if (module.hot) {
// Support hot reloading of components
// and display an overlay for runtime errors
const renderApp = render;
const renderError = (error) => {
const RedBox = require('redbox-react').default;
ReactDOM.render(
<RedBox error={error} />,
rootEl,
);
};
// In development, we wrap the rendering function to catch errors,
// and if something breaks, log the error and render it to the screen
render = () => {
try {
renderApp();
} catch(error) {
console.error(error);
renderError(error);
}
};
// Whenever the App component file or one of its dependencies
// is changed, re-import the updated component and re-render it
module.hot.accept('./containers/App', () => {
setTimeout(render);
});
}
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment