'How to update location.state in react-router v6?

I'm using react-router-dom v6. When using useNavigate like this:

let navigate = useNavigate();
navigate("/", {state: state});

I can access it by useLocation().location.state

My question is how to remove this state after i don't need it, for example in useEffect cleanup function.



Solution 1:[1]

My question is how to remove this state after I don't need it

You could read the passed route state into local component state and issue a redirect without state to the current path to clear out the state. This would prevent any back navigations to the page to retain any route state.

Example:

const Component = () => {
  const location = useLocation();
  const navigate = useNavigate();

  const [state] = useState(location.state || {}); // <-- cache state locally

  useEffect(() => {
    navigate(".", { replace: true }); // <-- redirect to current path w/o state
  }, [navigate]);

  return ( ... );
};

Edit how-to-update-location-state-in-react-router-v6

Solution 2:[2]

You should import useNavigate from react-router-dom:

import { useNavigate } from 'react-router-dom';

then make a variable:

const navigate = useNavigate();

then:

<button onClick={() => navigate('/')}><button>

And you are done.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese
Solution 2 Saeed Zhiany