When I am entering one page of the app I pass data through location state using react-router. Then I access it via location.state.myDataObject
. When I refresh the page it is still there, while I would like it to be empty. Here's what I've try to use:
const resetLocation = () => {
history.replace({
...location,
state: undefined,
});
};
useEffect(() => {
window.addEventListener('onbeforeunload', resetLocation);
}, []);
Or adding it to unmount
action within useEffect
but I guess it is not called when refreshing the page:
useEffect(() => {
return function cleanLocationState() {
history.replace({
...this.props.location,
state: undefined,
});
};
}, []);
To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON.
In React Router v6 you can do: const location = useLocation(); const navigate = useNavigate(); const state = location. state; // Do some stuff with the state // ... // Clear the state after navigate(location. pathname, { replace: true });
React-router resets all states of App component when I change route.
react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.
I think this is the desired behavior of react router. If you want to reset the state then you need to do something like
import React, { useEffect, useCallback } from "react";
import { useLocation, useHistory } from "react-router-dom";
function Home() {
const location = useLocation();
const history = useHistory();
const replaceHistory = useCallback(() => {
history.replace({ ...location, state: undefined });
}, [history]);
useEffect(() => {
window.addEventListener("beforeunload", () => replaceHistory);
return () => {
window.removeEventListener("beforeunload", replaceHistory);
};
}, []);
return (
<div>
<h2>Home</h2>
</div>
);
}
export default Home;
Working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With