0%
April 22, 2025

useBlocker hook to Block the Change of Route for Unsaved Update

react

1export default function SomePage() {
2
3  const hasUpdate = useAppSelector((s) => s.someDomain.hasUpdate);

Here we control whether a traffic should be blocked by a state variable. Then we plug this into our useBlocker hook:

4  useBlocker(({ currentLocation, nextLocation }) => {
5
6    let shouldBlock = false;
7
8    const hasRouteChange = nextLocation.pathname !== currentLocation.pathname;
9
10    if (hasUpdate && hasRouteChange) {
11      const shouldProceed = window.confirm(
12        "You have unsaved changes. Are you sure you want to leave?"
13      );
14      shouldBlock = !shouldProceed;
15    }
16
17    return shouldBlock;
18  });