useBeforeLeave

useBeforeLeave registers a listener that will be called prior to leaving the current location.


Import

import { useBeforeLeave } from "@solidjs/router";

Type

interface BeforeLeaveEventArgs {
from: Location;
to: string | number;
options?: Partial<NavigateOptions>;
readonly defaultPrevented: boolean;
preventDefault(): void;
retry(force?: boolean): void;
}
function useBeforeLeave(listener: (event: BeforeLeaveEventArgs) => void): void;

Parameters

listener

  • Type: (event: BeforeLeaveEventArgs) => void
  • Required: Yes

Function called before navigation leaves the current location.

The listener receives one argument with these fields and methods:

NameTypeDefaultDescription
fromLocationN/ACurrent location before the change.
tostring | numberN/ATarget passed to navigate.
optionsPartial<NavigateOptions> | undefinedundefinedOptions passed to navigate.
preventDefault() => voidN/ABlocks the route change.
defaultPreventedreadonly booleanfalsetrue after this handler or an earlier leave handler calls preventDefault().
retry(force?: boolean) => voidN/ARetries the same navigation. Pass true to skip running leave handlers again.

Return value

  • Type: void

useBeforeLeave does not return a value.


Behavior

  • The subscription is tied to the current owner and is removed during cleanup.
  • The event contains the current location in from, the next target in to, and navigation options in options.
  • Calling event.preventDefault() sets event.defaultPrevented and blocks the current navigation.
  • Calling event.retry(true) retries the same navigation and skips the before-leave lifecycle for that retry.

Examples

Basic usage

import { useBeforeLeave } from "@solidjs/router";
function Editor(props: { isDirty: () => boolean }) {
useBeforeLeave((event) => {
if (props.isDirty() && !event.defaultPrevented) {
event.preventDefault();
}
});
return <form>{/* fields */}</form>;
}

Last updated: 5/6/26, 4:10 AMEdit this pageReport an issue with this page