Source:  Twitter logo

I have a use case where i want to render a confirmation box when user ties close a browser tab in my react application.

I have a queue which contains the requests to be made to the backend server. I want to render confirmation dialog with some custom message if queue is not empty and user closes browser tab.

Are there any recommended libraries or workflow hwich I should follow to achieve this??

You can use window.onbeforeunload function, to show a popup before closing the browser window.

Eg: Inside the componentDidMount of your component, write the following code:

window.onbeforeunload = function(e) {
  if( //queue not empty ) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;

This is not in anyway related to React, but just a function provided by the window object. Also check browser compatibility

4 users liked answer #0dislike answer #04
Dane profile pic
import { useEffect, useState } from 'react';

 * Confirm browser exit.
 * @param defaultEnabled Start as enabled?
 * @param message Custom message (old browsers only).
 * @see
export const useConfirmBrowserExit = (
  defaultEnabled = true,
  message = 'Confirm leave page'
) => {
  const [msg, setMsg] = useState<string>(message);
  const [enabled, setEnabled] = useState<boolean>(defaultEnabled);

  useEffect(() => {
    function listener(e: BeforeUnloadEvent) {
      if (enabled) {
        e.returnValue = msg;
        return msg;

    window.addEventListener('beforeunload', listener);

    return () => {
      window.removeEventListener('beforeunload', listener);
  }, [msg, enabled]);

  return {
    enable(): void {
    disable(): void {
    setMessage(newMessage: string): void {
    getMessage(): string {
      return msg;
    setEnabled(status: boolean): void {
    getEnabled(): boolean {
      return enabled;



The support for custom messages have been removed.

2 users liked answer #1dislike answer #12
Eduardo Cuomo profile pic
Eduardo Cuomo

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).