reactjsreact-router-domwindow.location

Does the state will lose when refresh page in react-router v6?


The answers on Internet is Yes, but when I try to refresh on the page, the state params still exist.

so the question is: will the params passed by state in react-router lose when refresh page, or the react-router v6 improve the method of achieving state so that it won't lose

here is the sample code:

const navigate = useNavigate();

navigate('/path/to/newpage', {
   state: {
             name: 'lucy',
             age: 20
          }
});

When I refresh the page, the params won't lose.


Solution

  • No, the state will not be lost when refreshing the page in React Router v6.

    React Router v6 uses the new History API to manage the browser history, which allows it to maintain the state even when the page is refreshed. This means that the components and their states will be preserved when the user refreshes the page, as long as the URL remains the same.

    However, if the user refreshes the page and changes the URL, then the component and its state will be reset, as the new URL will trigger a new component to render.

    It is also worth noting that the behavior may differ depending on how your app is hosted and deployed. If your app is served statically, then refreshing the page may cause the server to return a new HTML document, which could potentially cause the state to be lost. To avoid this, you may need to configure your server to always serve the same HTML document regardless of the URL