Skip to main content

Navigation Blocking

Learn how to block navigation and prompt users before they leave a page with unsaved changes.

Overview

React Router provides the useBlocker hook to prevent navigation and prompt users when they attempt to leave a page. This is useful for forms with unsaved changes, preventing accidental data loss.

Basic Navigation Blocking

Block navigation when there are unsaved changes:

Blocker States

The blocker has three possible states:

Conditional Blocking

Block navigation only under specific conditions:

Blocker with Form State

Reset blocker after successful form submission:

Custom Confirmation Dialog

Create a reusable confirmation dialog:

Multiple Blockers

Handle multiple blocking conditions:

Browser Confirmation

Combine with browser’s native confirmation for external navigation:

Blocking with Route Parameters

Block navigation based on route changes:

Keyboard Shortcuts

Handle keyboard shortcuts while navigation is blocked:

Auto-save Integration

Combine blocking with auto-save:

Best Practices

  1. Only block when necessary - Don’t block if form is empty or unchanged
  2. Allow same-route navigation - Don’t block form submissions to the same route
  3. Clear state on success - Reset blocking after successful submission
  4. Provide clear messaging - Tell users why they’re being blocked
  5. Handle browser navigation - Use beforeunload for external navigation
  6. Make dialogs accessible - Use proper ARIA labels and keyboard navigation
  7. Consider auto-save - Reduce the need for blocking entirely
  8. Test thoroughly - Ensure blocking works across all navigation methods