Skip to Content
ohooks

useBeforeUnload

Prompts the user with a confirmation dialog before leaving or reloading the page.

Loading preview...

The useBeforeUnload hook attaches a beforeunload listener to window to warn users about unsaved changes before they close the tab, reload, or navigate away.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useBeforeUnload.json

Usage

Examples

Unsaved Form Changes

Pass a boolean flag so the browser only prompts the user when the form has unsaved edits.

Predicate Function

Pass a predicate function as the first argument to evaluate the condition lazily when the beforeunload event fires.

API Reference

Parameters

ParameterTypeDefaultDescription
enabledboolean | (() => boolean)trueWhether the confirmation prompt is active, or a predicate evaluated when beforeunload fires.
messagestringundefinedOptional legacy message assigned to event.returnValue.