The issue is likely due to how the popstate event works in combination with React's StrictMode and how you're handling the event listener. Here are the key problems and solutions:
Why You're Not Seeing the Logs:
-
Event Listener Reference: When StrictMode unmounts and remounts your component, the handlePopState function is recreated, but the event listener from the first mount is still active. The cleanup removes the first listener, but the second mount adds a new one.
-
popstate Event Timing: The popstate event fires when the user navigates through history (e.g., using the back/forward buttons). If you're changing pages programmatically (e.g., via changePage), the popstate event might not fire unless you explicitly trigger it.
-
StrictMode Double-Mounting: React's StrictMode intentionally unmounts and remounts components in development to test cleanup logic. This can interfere with event listeners.
How to Fix It:
Option 1: Use useCallback to Stabilize the Function
export default () => {
const hasMounted = useRef(false);
const handlePopState = useCallback((e: PopStateEvent) => {
console.log("Reached 1"); // Now this will log consistently
const stateAction: StateAction | undefined = e.state?.stateAction;
if (!stateAction) return;
e.preventDefault();
e.stopPropagation();
vmatch(stateAction, {
ChangePage: ({ page }) => changePage(page),
TopPagerBack: () => popTopPage(),
});
}, []); // No dependencies needed if `changePage`, `popTopPage`, and `vmatch` are stable
useEffect(() => {
if (hasMounted.current) return;
hasMounted.current = true;
const stateAction: StateAction = {
variant: "ChangePage",
page: { variant: "Admin" },
};
history.replaceState({ stateAction }, "", window.location.href);
window.addEventListener("popstate", handlePopState);
return () => {
window.removeEventListener("popstate", handlePopState);
};
}, [handlePopState]); // Add `handlePopState` as a dependency
return <span style={{ display: "none" }}></span>;
};
Option 2: Manually Trigger popstate When Changing Pages
If you're changing pages programmatically (e.g., via changePage), you might need to manually dispatch a popstate event to ensure the handler runs:
const changePage = (page: Page) => {
// Your existing page-changing logic
window.dispatchEvent(new PopStateEvent("popstate", { state: { stateAction: { variant: "ChangePage", page } } }));
};
Option 3: Debugging Steps
-
Check if popstate is firing at all:
Add a global listener to see if the event is being triggered:
useEffect(() => {
const globalListener = () => console.log("Global popstate fired");
window.addEventListener("popstate", globalListener);
return () => window.removeEventListener("popstate", globalListener);
}, []);
-
Verify e.state:
Ensure the state you're pushing to history is correct:
const stateAction: StateAction = { variant: "ChangePage", page: { variant: "Admin" } };
history.replaceState({ stateAction }, "", window.location.href);
console.log("Current state:", history.state); // Debug the state
-
Test Without StrictMode:
Temporarily disable StrictMode in your app to see if the issue persists. If it works, the problem is likely related to StrictMode's double-mounting.
Key Takeaways:
- Use
useCallback to stabilize the handlePopState function.
- Ensure the
popstate event is being triggered (it doesn't fire for pushState/replaceState unless you manually dispatch it).
- Debug the state and event flow to confirm everything is wired correctly.