Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 50 ยท Navigating Programmatically

Blocking Navigation

Stop users from losing work: use React Router's useBlocker for in-app navigation, beforeunload for tab closes, and learn the pitfalls of unsaved form changes.

You have typed a long message into a form, you click a link by accident, and everything is gone. Apps that edit data (documents, settings, checkout forms) need a way to say "wait, you have unsaved changes". That is called blocking navigation: the app notices the user is about to leave, pauses the move, and asks for confirmation.

There are two different ways a user can leave, and they need two different tools. Leaving to another route inside your app (a link click, a back button press, a navigate() call) is handled by React Router's useBlocker hook. Leaving the page itself (closing the tab, reloading, typing another address) never goes through the router at all, so it is handled by the browser's beforeunload event. A good unsaved-changes guard uses both.

useBlocker in React Router

useBlocker takes a condition and returns a blocker object. While the condition is true, any navigation inside the app is stopped, and the blocker tells you about it so you can show your own dialog.

useBlocker only works with a data router: createBrowserRouter, createHashRouter or createMemoryRouter with <RouterProvider>. Using it under plain <BrowserRouter> throws an error. See createBrowserRouter and RouterProvider for the setup.

This is the real React Router API, shown read-only:

JSX
// Real React Router (data mode), read-only
import { useState } from 'react';
import { useBlocker } from 'react-router';

export function Editor() {
  const [saved, setSaved] = useState('');
  const [draft, setDraft] = useState('');
  const isDirty = draft !== saved;

  const blocker = useBlocker(isDirty);

  return (
    <div>
      <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />
      <button onClick={() => setSaved(draft)}>Save</button>

      {blocker.state === 'blocked' && (
        <dialog open>
          <p>You have unsaved changes. Leave anyway?</p>
          <button onClick={() => blocker.reset()}>Stay</button>
          <button onClick={() => blocker.proceed()}>Leave</button>
        </dialog>
      )}
    </div>
  );
}

The blocker moves through three states:

stateDiagram-v2
  [*] --> unblocked
  unblocked --> blocked : navigation attempted while blocking
  blocked --> proceeding : blocker.proceed()
  blocked --> unblocked : blocker.reset()
  proceeding --> unblocked : navigation completes

A blocker rests in "unblocked", enters "blocked" when navigation is stopped, and you choose "proceed" or "reset".

  • unblocked: nothing is being blocked right now. This is the normal state.
  • blocked: the user tried to leave while your condition was true. The navigation is paused. blocker.location holds the place they wanted to go, so your dialog can mention it.
  • proceeding: you called blocker.proceed() and the pending navigation is now completing.

blocker.proceed() lets the paused navigation continue. blocker.reset() cancels it and returns to unblocked. If the user pressed the browser's back button, the router has already restored the old URL while the dialog is open, so staying really leaves everything as it was.

Try it: a blocked navigation

This stand-in imitates the useBlocker hook with window.location.hash. It has the same state, proceed, reset and location fields. Edit the text, then click a link. A dialog appears instead of the page change. Use Save and the blocker goes away.

The sandboxed preview cannot show the browser's own confirm() dialog (it is blocked), and neither should you rely on it in a real app: render the question in your own UI, which can be styled and made accessible.

A useBlocker stand-in with a confirmation dialog

The stand-in does the same job as useBlocker in this situation, but it is far simpler than the real hook: it handles only top-level hash changes, and the real router also knows about history positions so it can undo a back or forward press exactly.

Blocking only the navigations that matter

Not every navigation away from the form loses data. Switching a tab inside the editor with a search param (/editor?tab=preview) keeps the same component mounted and the same draft. Blocking that would be annoying. So useBlocker also accepts a function, which receives the current and next location and returns whether to block:

JSX
// Real React Router, read-only
const blocker = useBlocker(
  ({ currentLocation, nextLocation }) =>
    isDirty && currentLocation.pathname !== nextLocation.pathname
);

The function form can also look at historyAction ('PUSH', 'POP' or 'REPLACE'), for example to let REPLACE navigations through. The next example evaluates three different rules against four navigations so you can see what each one blocks. Toggle the dirty flag and compare the columns.

Which navigations does each rule block?

With the checkbox ticked, the first rule blocks all four moves, the second blocks every move that changes the pathname (including /editor to /editor/history), and the third only blocks the two moves that leave the /editor area. Pick the narrowest rule that protects the user's data.

Closing the tab: beforeunload

When the user closes the tab or reloads, the router is never asked. The browser fires a beforeunload event on window, and if a listener calls event.preventDefault(), the browser shows its own generic confirmation ("Leave site? Changes you made may not be saved"). You cannot customize that text; browsers removed custom messages years ago to stop scams.

JSX
// Read-only: a real page is needed, the live preview cannot show the browser prompt
import { useEffect } from 'react';

function useWarnBeforeUnload(when) {
  useEffect(() => {
    if (!when) {
      return;
    }
    const handler = (event) => {
      event.preventDefault();
      event.returnValue = ''; // older browsers still look for this
    };
    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [when]);
}

Only add the listener while there is something to lose. A permanent beforeunload listener annoys users and can stop the browser from putting the page into its fast back/forward cache. Browsers also show the prompt only if the user has interacted with the page, which is why you cannot use it as a trap.

Pitfalls

Navigating right after saving gets blocked. Suppose a save handler runs setSaved(draft) and then navigate('/documents') on the next line. State updates are batched, so the blocker still sees isDirty === true and blocks your own navigation. Navigate from an effect that runs after the save finished (for example useEffect(() => { if (didSave) navigate('/documents'); }, [didSave])), or call blocker.proceed() when the blocker fires and the save was successful. The function form helps too, because it can check a ref that you set synchronously.

Do not block too much. A dialog on every click trains people to click "Leave" without reading. Block only when real data would be lost, and prefer other designs where you can: autosave drafts, or keep the text in the URL or in a store so coming back restores it.

Accessibility. A custom dialog must take focus when it opens, trap focus while it is open, close on Escape (which should behave like "Stay") and return focus afterwards. The native <dialog> element with showModal() does most of this for you. The stand-in above skips it to stay short.

Router version history. React Router version 5 had a <Prompt> component for this. It was removed in version 6, and useBlocker (introduced for data routers) is its replacement. If you migrate old code, see the migration guide.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tool catches the user closing the browser tab, and why not useBlocker?

    useBlocker only sees navigations handled by the router. Closing or reloading the page is handled by the browser, which fires beforeunload on window.
  2. 2. What does blocker.reset() do when the state is 'blocked'?

    proceed() continues the navigation, reset() cancels it. In both cases the blocker ends up unblocked again.
  3. 3. Where does useBlocker work?

    useBlocker needs the data router's navigation machinery. Under <BrowserRouter> it throws an error.
  4. 4. Why use the function form useBlocker(({ currentLocation, nextLocation }) => ...)?

    The function receives both locations, so you can block only the moves that really lose data, for example when the pathname changes.

Summary

  • Use useBlocker (data routers only) to stop in-app navigation while the user has unsaved changes. The blocker's state is unblocked, blocked or proceeding, and you call proceed() or reset() from your own dialog.
  • Pass a function to the hook to block only the navigations that lose data, such as a pathname change.
  • Use a beforeunload listener, added only while the form is dirty, for closing or reloading the tab. Its message cannot be customized.
  • Beware of blocking your own navigation right after saving, and prefer autosave or URL state where you can.
  • The live example is a stand-in. Copy the read-only code into a data-router project to use the real hook.

Next: createBrowserRouter and RouterProvider