Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

react-beforeunload

> 编程语言
Open source

:door: React component and hook which listens to the beforeunload window event.

199 stars0 likes3 views
WebsiteGitHub

About

:door: React component and hook which listens to the beforeunload window event.

react-beforeunload

Listen to the beforeunload window event in React.

Usage

useBeforeunload Hook (recommended)

javascript
useBeforeunload(handler);

Parameters

  • handler optional function to be called with BeforeUnloadEvent when beforeunload event is fired. Passing a non-function value will disable the event listener.

Example

Simple
javascript
import { useBeforeunload } from "react-beforeunload";

const Example = (props) => {
  useBeforeunload((event) => event.preventDefault());
  ...
};
Conditional
javascript
import { useBeforeunload } from "react-beforeunload";

const Example = (props) => {
  const [value, setValue] = useState("");

  useBeforeunload(value !== "" ? (event) => event.preventDefault() : null);
  // or
  useBeforeunload(value !== "" && () => true);

  ...
};

Beforeunload Component

javascript

Props

  • onBeforeunload function to be called with BeforeUnloadEvent when beforeunload event is fired.

Example

javascript
import { Beforeunload } from "react-beforeunload";

class Example extends React.Component {
  state = { value: "" };

  render() {
    return (
      <>
        {this.state.value !== "" && (
           event.preventDefault()} />
        )}
         this.setState({ value: event.target.value })}
          value={this.state.value}
        />
      
    );
  }
}

:information_source: The Beforeunload component will render any children passed as-is, so it can be used as a wrapper component:

javascript

  

Custom message support

:warning: Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers.

Source

To display a custom message in the triggered dialog box, return a string in the passed event handler function.

With useBeforeunload hook:

javascript
useBeforeunload(() => "You’ll lose your data!");

With Beforeunload component:

javascript
 "You’ll lose your data!"} />

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言