Hooks

useBeforeUnload

A custom hook to handle the beforeunload event in React applications

Example

import { useBeforeUnload } from '@vitnode/core/hooks/use-before-unload'
export const CustomMessageExample = () => {
  const [isEditing, setIsEditing] = useState(false)

  useBeforeUnload(
    isEditing,
    'You have unsaved changes. Are you sure you want to leave?',
  )

  return (
    <div>
      <button onClick={() => setIsEditing(true)}>Start editing</button>
      <p>Note: Modern browsers may not show the custom message</p>
    </div>
  )
}

On this page