[SOLVED] React Router Dom useNavigate causes reload/re-render of the whole application and thereby clearing all state

Issue

This Content is from Stack Overflow. Question asked by Drizzle

When I want to perform a programmatic navigation or a return navigation on button click, React useNavigate() causes all state, redux and context to revert to initial. eg

                <IconButton 
                onClick={()=>{
                    navigate(-1)
                }}>Go back
                </IconButton>

on clicking to return to previous page, all states on the page are reverted to initial state.
Please is there any solution?

And yes I have tried the following

                <IconButton 
                onClick={()=>{
                    navigate(-1, { replace: true })
                }}>Go Back
                </IconButton>

and…

                <IconButton 
                onClick={()=>{
                    navigate(-1, { replace: false })
                }}>Go back
                </IconButton>

And none works. How do I keep the previous state when I perform a programmatic navigation?



Solution

I think that if you are navigating using react-router’s link elements or pushing to its history between Parent and Child elements then the state of the parent components should be preserved.
But If you are navigating between siblings then to persist the state you’ll need to use some sort of storage (session storage, local storage, or reading from some DB)

Another solution would be using a Higher-order-component that would be the top-level component (Higher than react-router), so when the location has changed, you don’t lose the information in the state. in another word, you have to have a general state.


This Question was asked in StackOverflow by Drizzle and Answered by Aymane It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?