Skip to main content

Race Condition Handling

Race conditions occur when the order of async operations affects correctness. React Router automatically prevents the most common UI race conditions.

What React Router Prevents

React Router handles race conditions in:
  1. Navigation: Interrupted navigations are cancelled
  2. Form submissions: Interrupted submissions are cancelled
  3. Revalidation: Stale revalidations are discarded
  4. Fetcher requests: Self-interrupting requests are cancelled

Browser-Inspired Behavior

React Router mirrors browser behavior: Browser: Click Link A, then Link B before A loads → A is cancelled, B proceeds React Router: Same behavior with client-side routing

Form Submission

Browser: Submit Form A, then Form B before A completes → A is cancelled, B proceeds React Router: Same behavior with Form components

Problem: Stale Navigation

Without cancellation, slow requests could overwrite newer navigations:

Solution: Automatic Cancellation

React Router cancels in-flight requests:

Revalidation Race Conditions

Problem: Out-of-Order Revalidation

Multiple actions can trigger overlapping revalidations:

Solution: Discard Stale Revalidation

React Router tracks request timing:
When action 2’s revalidation completes before action 1’s, action 1’s data is discarded.

Fetcher Race Conditions

Self-Interrupting Fetchers

Fetchers cancel their own previous requests:

Independent Fetchers

Different fetcher instances don’t cancel each other:

Type-Ahead Search Example

Common race condition scenario:

Solution

React Router automatically cancels:

Optimistic UI Race Conditions

Problem: Failed Optimistic Updates

Solution: Revert on Error

Server Race Conditions

React Router only prevents client race conditions. Server race conditions require server-side solutions.

Problem: Backend Race Condition

Solutions

Optimistic Locking:
Timestamps:
Request Tokens:

Request Abortion

Detect when requests are cancelled:
Manual abortion check:

Polling Race Conditions

Problem: Overlapping Polls

Solution: Wait for Completion

Testing Race Conditions

Simulate race conditions in tests:

Best Practices

  1. Trust automatic cancellation: React Router handles it
  2. Handle server race conditions: Use locks, timestamps, or tokens
  3. Revert optimistic failures: Show error and original state
  4. Pass abort signals: To fetch() for proper cleanup
  5. Test rapid interactions: Simulate race conditions

What React Router Doesn’t Prevent

❌ Server-side race conditions
❌ Race conditions between different apps
❌ WebSocket message ordering
❌ Browser storage conflicts