I wanted my modal state to survive page reloads, so I persisted it in sessionStorage:
{
"isOpen": true,
"activeModal": "addFile",
"mode": "addFile"
}
Problem:
When navigating to a different route, the modal should auto-close ✅
But on refresh, React remounts → effect runs → modal closes ❌
Final clean fix
import { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import { useModalStore } from "@/store/useModalStore";
export const useAutoCloseModalOnRouteChange = () => {
const { pathname } = useLocation();
const prevPath = useRef(pathname);
useEffect(() => {
const store = useModalStore.getState();
// ✅ Only close if the route *actually* changed
if (prevPath.current !== pathname && store.isOpen) {
store.closeModal();
}
prevPath.current = pathname;
}, [pathname]);
};
✅ Closes modal only on real navigation
✅ Modal stays open on page refresh
✅ Works with Zustand + sessionStorage
✅ No infinite loops
✅ No permissions required browsers allow sessionStorage by default
✅ Short feedback
This approach is clean because:
You don’t add closeModal to dependencies (avoids re-renders)
No infinite loops (not watching isOpen)
Fully independent from the UI can be dropped into any route-based modal
Nice little pattern for URL-synced modals 👌
Top comments (0)