Search code examples
reactjswebpackreduxreact-hot-loaderhot-reload

page refreshes when file is changed react


I have a react/redux app and when file changes and I hit save it refreshes the page and clears all redux data.I know t that I can persist redux data to localstorage. What I would love to know is that is it the default behaviour of react/node server to refresh the page when file changes? If not how can I prevent it?


Solution

  • Is it a default behaviour? : YES, it is.

    This is known as live-reloading where a change in your file refreshes your local server and restarts the app setting all state to initial ones.

    But the problem as you mentioned is that the state of the app is lost.

    There is another concept called hot-reloading which prevents it. Hot reloading will just replace the modules which have changed while the app is running. This won't cause a total refresh of the app. It will just update the page with the changes without a reload, and so will maintain the state of the app. However, the state of the component,i.e, the react state isn't maintained.

    Now, when you create a react project using CRA, the hot reload feature is built in. You can try it by running your app and changing some css. You will notice that the app doesn't refresh but the changes are applied!!

    However, if you try doing this in a JSX file, the entire app changes. This is because there are some changes that needs to be done to enable hot reloading in a JSX file.

    Go to the index.js and write this line of code:

    if (module.hot && process.env.NODE_ENV !== 'production') {
      module.hot.accept();
    }
    

    If you go and make a change to your JSX file now, you will see that the updates are applied without refresh.

    BUT, the react state aren't maintained. There is a library called the react-hot-loader, which can help you in maintaining the react state too.Try it out!