2

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?

1 Answer 1

7

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!

Sign up to request clarification or add additional context in comments.

8 Comments

thanks @Rohan for quick reply, In I remember it did not used to refresh the page but then I dont know what happened. I even tried to reinstall chrome, delete node modules and install them again but nothing worked :(
Sorry, didn't get you. Did you try by adding the code mentioned above in your index.js or index.ts file? This will prevent refreshing the app.
yes I added and it seems to work, but as you said react states wont be saved?
Yes for that as I mentioned , you need to use the react-hot-loader plugin and make some configuration changes. You can find many good articles on the web to do it. :)
last question :), the module variable in your code, which package includes it? maybe 'react'?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.