Reputation: 585
While working on a project I noticed a weird behavior of the useLocation
hook that I can`t find an explanation to.
I have a button that when clicked it will redirect you to an EditOrder
page and will pass a state with it:
const navigate = useNavigate();
const handleClick = (data) => {
navigate("edit-order", {state: {order: data}})
};
In the EditOrder
page I check with a UseEffect
hook if a state
was provided and if not the user will be redirected to a different page:
const { state } = useLocation();
const navigate = useNavigate();
useEffect(() => {
if (!state) {
navigate("some-page");
}
}, []);
The weird part is when I refresh the page I can still access it, and if I console.log(state.order)
the data is still there, even when I reload with ctrl + shift + r
the state stays the same, and this also happens with the empty cache and hard reload option
(tried in both chrome and edge).
But when I copy the URL and past it in a new tab I immediately get redirected to "some-page"
and console.log(state)
will show null
.
I checked both the cookies and local storage and I can't find the state data there.
Can someone explain why is this happening and how the state data is being saved?
Edit:
Here is a youtube video that shows this behavior.
The code on the video can be found in this sandbox, when you run the code on sandbox it runs as it should, on refresh all the states reset, but when running locally this problem occurs (on 2 different computers).
A git repo about location.state
Upvotes: 6
Views: 4917
Reputation: 3051
React's useLocation is based on the history library, which uses the BrowserHistory
in web apps.
Some browsers, like Chrome, persist BrowserHistory
state between sessions, while others (like Firefox) do not.
This is likely why you're seeing this behavior locally but not in a Sandbox. It appears that CodeSandbox's browser clears history state on refresh. It's also why, if you copy the URL into another tab, the redirect works. BrowserHistory
is local to a single tab.
In short, this is intended behavior. Either you need to clear the history state manually or store your application state elsewhere (useContext
could be a good choice if you want to persist across pages but not across a refresh).
Upvotes: 9