useLeavePageConfirmation is a custom hook designed to prompt users with a confirmation dialog before they navigate away from a page with unsaved changes. It encapsulates the logic for detecting page navigation attempts and displaying a customizable confirmation message.
As frontend developers, we're always striving to create seamless and intuitive user experiences in our web applications. One common scenario we encounter is when users attempt to navigate away from a page with unsaved changes. In such cases, providing a confirmation dialog can prevent accidental data loss and enhance user satisfaction. In this blog post, I'll introduce you to useLeavePageConfirmation
, a TypeScript custom hook that simplifies the implementation of leave page confirmation dialogs in React applications.
Why useLeavePageConfirmation?
Implementing leave page confirmation dialogs manually can be cumbersome and error-prone. With useLeavePageConfirmation
, you can abstract away this complexity into a reusable hook, making it easy to add this functionality to any React component.
How it Works
To detect when user leave the page in browser we need to use the the beforeunload
event.
The beforeunload
event is fired when the current window, contained document, and associated resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.
The main use case for this event is to trigger a browser-generated confirmation dialog that asks users to confirm if they really want to leave the page when they try to close or reload it, or navigate somewhere else. This is intended to help prevent loss of unsaved data. You can read more information about this event here https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
When you understood the beforeunload
event already, Let's dive into the implementation of useLeavePageConfirmation
:
import { useEffect } from 'react';
const useLeavePageConfirmation = (isDirty: boolean, confirmationMessage: string) => {
useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (isDirty) {
event.preventDefault();
event.returnValue = confirmationMessage;
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [isDirty, confirmationMessage]);
};
export default useLeavePageConfirmation;
How to Use useLeavePageConfirmation
Here's how you can use useLeavePageConfirmation
in your React components:
import React, { useState } from 'react';
import useLeavePageConfirmation from './useLeavePageConfirmation';
const MyComponent: React.FC = () => {
const [isDirty, setIsDirty] = useState(false);
useLeavePageConfirmation(isDirty, 'You have unsaved changes. Are you sure you want to leave?');
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setIsDirty(true);
// Handle input change...
};
return (
<div>
<input type="text" onChange={handleInputChange} />
{/* Additional component content... */}
</div>
);
};
export default MyComponent;
In this example, useLeavePageConfirmation
is called with two parameters: isDirty
, a boolean indicating whether there are unsaved changes, and confirmationMessage
, the message to display in the confirmation dialog. The hook listens for beforeunload
events and displays the confirmation dialog if isDirty
is true.
Benefits of useLeavePageConfirmation
- Improved User Experience: By providing users with a confirmation dialog before leaving a page with unsaved changes, you reduce the risk of data loss and enhance user satisfaction.
- Reusable and Maintainable:
useLeavePageConfirmation
encapsulates the leave page confirmation logic, making it easy to reuse across multiple components and maintain consistency in your application. - Customizable: You can customize the confirmation message according to your application's specific requirements, providing users with clear and informative prompts.
Conclusion
In conclusion, useLeavePageConfirmation
is a valuable tool for enhancing the user experience in React applications by adding leave page confirmation dialogs. With its simple and reusable interface, you can easily integrate this functionality into your components and ensure a smoother navigation experience for your users. So why not give it a try in your next project?
If you guys have any question let put the comment in the section below. Thanks!
Happy coding!
Discussion (undefined)