May 28, 2023

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

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 ( ... );
};

Leave a Reply