Skip to main content

useNavigation()

Modern React architectures are fragmented across several major routing libraries (Next.js App Router, React Router plugin, TanStack, etc.), each with vastly different imperative APIs for pushing or replacing routes. The useNavigation() hook abstracts away this framework-level complexity. It exposes a universal, normalized interface for triggering client-side redirects that elegantly patches over whichever router configuration you happen to have active beneath the top-level Wacht <DeploymentProvider />.

Import

import { useNavigation } from "@wacht/react-router";

Anatomy

const {
  push,     // Appends a new route to the browser's history stack
  replace,  // Overwrites the current history entry
  goBack    // Navigates one step backwards in the history stack
} = useNavigation();

Usage

This hook is incredibly valuable when authoring platform-agnostic UI libraries or when building complex custom components that need to defensively redirect out of invalid states.
import { useNavigation } from "@wacht/react-router";

export function CancelButton() {
  const { replace, goBack } = useNavigation();

  // Triggered when a user aborts an onboarding flow
  const handleCancelClick = () => {
    // Attempt to gracefully retreat one step logically
    goBack();
    
    // In scenarios where goBack() might fail (e.g. they landed directly 
    // on this nested page), you could alternatively enforce a hard replace:
    // replace("/dashboard");
  };

  return (
    <button 
      onClick={handleCancelClick}
      className="text-zinc-600 hover:text-red-600 font-medium px-4 py-2"
    >
      Cancel and Return
    </button>
  );
}