Use_Navigate_away

Function to perform certain things when a user navigates away from a page (does not cover all use cases)

Teecod3

View Profile
83 views
Jun 21, 2025
Updated Jun 21, 2025
'use client';

import { useEffect } from 'react';

export function useNavigationAway(
callback: () => void,
dependencies: any[] = [],
) {
useEffect(() => {
// Flag to track if navigation is internal
let isNavigatingInternally = false;

// Handler for internal navigation
const handleInternalNavigation = () => {
isNavigatingInternally = true;
};

// Add click listeners to internal navigation elements
const internalNavElements = document.querySelectorAll(
'a[href]:not([target="_blank"]), button[type="submit"], form',
);

internalNavElements.forEach((el) => {
el.addEventListener('click', handleInternalNavigation);
});

// Handle form submissions
const handleFormSubmit = () => {
isNavigatingInternally = true;
};

const forms = document.querySelectorAll('form');
forms.forEach((form) => {
form.addEventListener('submit', handleFormSubmit);
});

// Handle popstate (back/forward navigation)
window.addEventListener('popstate', handleInternalNavigation);

return () => {
// Cleanup: Remove event listeners
internalNavElements.forEach((el) => {
el.removeEventListener('click', handleInternalNavigation);
});

forms.forEach((form) => {
form.removeEventListener('submit', handleFormSubmit);
});

window.removeEventListener('popstate', handleInternalNavigation);

// Execute callback only if navigation is internal
if (isNavigatingInternally) {
callback();
}
};
}, [_..._dependencies]);
}