How to Close a React Modal with the Browser Back Button
If you call history.pushState() to add one history entry when the modal opens, the browser's back button can close only the modal. If you open and close the modal with useState alone and do not use history, pressing back takes you to the previous page. This applies to cases like an enlarged photo view or a filter panel where you want the back button to close only the modal.
However, when the modal is closed with the close button or the Esc key, the history entry you added also has to be undone. In my test environment, if it was not undone, the next back press changed nothing on screen. Also, if the close handler only called history.back(), double-clicking the close button went back to the previous page as well as closing the modal.
The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx with tsc, transpiled it with esbuild, and operated Chromium 153 through Playwright 1.63.0. The browser's back and forward actions were performed with Playwright's page.goBack() and page.goForward(). The app was wrapped in StrictMode and run with the React development build. I did not test browsers other than Chromium, the physical back button or gestures on a phone, or combinations with routing libraries such as React Router. Note that MDN's cancel event page says a mobile back button may act as a request to close a <dialog>.
- 1. With useState alone, "back" leaves the page
- 2. A hook that pushes a history entry on open and closes on popstate
- 3. Back closes the modal, forward reopens it
- 4. The close button and the Esc key also call history.back()
- 5. Preventing a double click from going back twice
- 6. Reloading while the modal is open
With useState alone, "back" leaves the page
For comparison, I first tried a version that opens and closes the modal with useState alone. I went from a link on the previous page to a photo list, opened the modal, and then pressed the browser's back button. page is the page title, dialogOpen shows whether the <dialog> is open, and state is history.state.
「写真を大きく見る」を押したあと: {"page":"写真の一覧","dialogOpen":true,"state":null}
ブラウザの「戻る」1回目のあと: {"page":"前のページ","dialogOpen":null,"state":null}
I omitted the line right after opening the list and the history.length entry from the output. Opening the modal did not add a history entry, so "back" moved to the page before the photo list, which is the previous page.
A hook that pushes a history entry on open and closes on popstate
So the hook pushes one history entry when the modal opens. Here is the full useHistoryModal hook I used for testing.
import { useCallback, useEffect, useRef, useState } from 'react';
type ModalHistoryState = { modal?: string } | null;
const currentModal = () => (history.state as ModalHistoryState)?.modal;
export function useHistoryModal(key: string) {
// When the page is reloaded, start in the open state if the current history entry records the modal
const [open, setOpen] = useState(() => currentModal() === key);
// Set to true from the call to history.back() until the popstate event arrives
const closingRef = useRef(false);
// When back or forward changes the history entry, match open to that entry's record
useEffect(() => {
const onPopState = () => {
closingRef.current = false;
setOpen(currentModal() === key);
};
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, [key]);
const show = useCallback(() => {
if (currentModal() !== key) {
// Keep the existing values in the current history.state and add modal to them
history.pushState({ ...history.state, modal: key }, '');
}
setOpen(true);
}, [key]);
const close = useCallback(() => {
if (currentModal() === key) {
if (closingRef.current) return; // Even if pressed repeatedly, go back only once
closingRef.current = true;
history.back(); // popstate fires here, and open becomes false there
} else {
setOpen(false);
}
}, [key]);
return { open, show, close };
}
In show, the first argument of pushState() is a value such as { modal: 'photo' }, which records "the modal is open" on the history entry. The second argument is not used at the moment, but it cannot be omitted. MDN's pushState() page says passing an empty string is safe against future changes. I left out the third argument, the URL. When it is omitted, the URL stays the current page's URL, so the address bar does not change.
When back or forward switches the history entry, a popstate event fires on window (MDN's popstate event page). The hook reads history.state at that point and decides open by whether modal equals its own key. The key point is that open or closed is decided only by the record on the history entry.
On the modal side, as in my article "How to Make a Modal with the HTML dialog Element in React," the component calls showModal() and close() on the <dialog> to match open. I passed the hook's close to both the close button and the <dialog>'s onClose.
import { useEffect, useRef } from 'react';
type Props = { open: boolean; onClose: () => void; title: string };
export function PhotoDialog({ open, onClose, title }: Props) {
const ref = useRef<HTMLDialogElement>(null);
// Match open: show or close the dialog as a modal
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
return (
// A close event also fires when the Esc key closes the dialog, so leave it to onClose
<dialog ref={ref} onClose={onClose} aria-label={title}>
<h2>{title}</h2>
<p>ブラウザの「戻る」でも閉じられます。</p>
<button type="button" onClick={onClose}>閉じる</button>
</dialog>
);
}
On the caller side, pass the open, show, and close returned by useHistoryModal('photo') to the button and the modal.
function Gallery() {
const { open, show, close } = useHistoryModal('photo');
return (
<main>
<h1>写真の一覧</h1>
<button type="button" className="open" onClick={show}>写真を大きく見る</button>
<PhotoDialog open={open} onClose={close} title="写真の詳細" />
</main>
);
}
I left out the code that selects the comparison version and the code that displays history.state on screen from the code I tested.
Back closes the modal, forward reopens it
These are the results of opening the modal with this hook and then pressing back and forward. I omitted the line right after opening the list and the history count entry from the output.
「写真を大きく見る」を押したあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
ブラウザの「戻る」1回目のあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
ブラウザの「進む」のあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
もう一度「戻る」のあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
さらに「戻る」のあと: {"page":"前のページ","dialogOpen":null,"state":null}
The first back closed only the modal and stayed on the photo list. history.state returned to null, the value from before the push. Pressing forward returned to the {"modal":"photo"} entry, so the modal opened again. Pressing back twice more closed the modal and then moved to the previous page. The previous page has no <dialog>, so dialogOpen is null.

The bar under the GIF shows history.state read after each action. The browser's back was performed with Playwright's page.goBack(), so the browser toolbar does not appear in the recording. To show the moment each press happens, the right side of the top bar displays "← Back".
The close button and the Esc key also call history.back()
If the close button only calls setOpen(false), the history entry that was pushed stays in place. I tried this with the comparison version.
「写真を大きく見る」を押したあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
「閉じる」を押したあと: {"page":"写真の一覧","dialogOpen":false,"state":{"modal":"photo"}}
ブラウザの「戻る」1回目のあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
ブラウザの「戻る」2回目のあと: {"page":"前のページ","dialogOpen":null,"state":null}
After closing, history.state was still {"modal":"photo"}. So the first back only moved one entry back to the leftover entry, and the screen did not change. Two presses of back were needed to reach the previous page.
The hook's close does not call setOpen(false) if the current entry has a modal record. Instead, it calls history.back(). Going back one entry fires popstate, and open becomes false along the same path as pressing back. Here are the results of the same operations with the hook.
「写真を大きく見る」を押したあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
「閉じる」を押したあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
もう一度開いたあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
Esc キーを押したあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
ブラウザの「戻る」1回目のあと: {"page":"前のページ","dialogOpen":null,"state":null}
Whether closed with "Close" or the Esc key, history.state returned to null, and one back press then moved to the previous page. When the Esc key closes the modal, the browser closes the <dialog> and fires a close event (MDN's dialog element page, MDN's cancel event page). Because onClose calls the hook's close, the history goes back one entry just as with the close button.
After popstate sets open to false, an effect calls dialog.close(). Closing with close() also fires a close event (MDN's close() page), so onClose is called once more. At that point the current entry has no modal record, so close only calls setOpen(false) and the history does not go back again.
In both the hook's output and the comparison version's output, history.length did not decrease after back and stayed at the same count as when the modal was opened. The hook determines the modal state from history.state, not from the number of history entries.
Preventing a double click from going back twice
history.back() is asynchronous. The history has not gone back at the time of the call, and completion is known only through popstate (MDN's back() page). So if close is called again before popstate arrives, history.state is still {"modal":"photo"}, and history.back() is called twice.
Here are the results of double-clicking "Close" with a version that removes the closingRef lines from the hook, and with the hook as written in this article. I omitted the history count entry from the output.
記事の版:「閉じる」をダブルクリックしたあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
closingRef なしの版:「閉じる」をダブルクリックしたあと: {"page":"前のページ","dialogOpen":null,"state":null}
In the version without closingRef, the modal closed and the page also went back to the previous page. The article's hook sets closingRef to true when it calls history.back(), and it does not call back a second time until popstate arrives. This value is not shown on screen, so I put it in a ref rather than in state (official useRef reference).
Reloading while the modal is open
The record on the entry pushed with pushState() stayed in history.state after a page reload. Here is the result of reloading with the modal open.
「写真を大きく見る」を押したあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
再読み込みのあと: {"page":"写真の一覧","dialogOpen":true,"state":{"modal":"photo"}}
「閉じる」を押したあと: {"page":"写真の一覧","dialogOpen":false,"state":null}
ブラウザの「戻る」1回目のあと: {"page":"前のページ","dialogOpen":null,"state":null}
The hook passes a function as the initial value to useState and reads history.state on the first render (official useState reference). After reloading, the modal still started open. Pressing "Close" went back one entry, and one more back press moved to the previous page.
Push one history entry with pushState() when opening, and use history.back() to go back on every kind of close. Decide open or closed in popstate by reading history.state, and do not call history.back() again until popstate arrives. In my tests, this kept the number of back presses and the modal state in sync.
This article keeps the modal state only in history.state and does not change the URL. If you pass a URL as the third argument of pushState(), the pushed entry gets that URL (MDN's pushState() page). For a way to switch the screen by extracting values from the URL, see my article "How to Extract Values from a URL in React with URLPattern."





