diff --git a/pages/hooks/_meta.json b/pages/hooks/_meta.json
index 37c2a64..d819af1 100644
--- a/pages/hooks/_meta.json
+++ b/pages/hooks/_meta.json
@@ -11,5 +11,6 @@
"use-persistent-state": "usePersistentState",
"use-query-params": "useQueryParams",
"use-timeout": "useTimeout",
+ "use-unsaved-form-changes": "useUnsavedFormChanges",
"use-url": "useUrl"
}
diff --git a/pages/hooks/use-unsaved-form-changes.mdx b/pages/hooks/use-unsaved-form-changes.mdx
new file mode 100644
index 0000000..70672a4
--- /dev/null
+++ b/pages/hooks/use-unsaved-form-changes.mdx
@@ -0,0 +1,85 @@
+# useUnsavedFormChanges
+
+
A custom hook to manage unsaved form changes and warn users before leaving the page.
+
+## Add hook
+
+Create a file `use-unsaved-form-changes.ts` and copy & paste the code from [useUnsavedFormChanges](/hooks/use-unsaved-form-changes#hook).
+
+## Usage
+
+```tsx {3,6}
+
+import React from 'react';
+import { useUnsavedFormChanges } from './hooks/use-unsaved-form-changes';
+
+function App() {
+ const { isFormChanged, setFormChanged } = useUnsavedFormChanges();
+
+ const handleChange = () => {
+ setFormChanged(true);
+ };
+
+ const handleSave = () => {
+ setFormChanged(false);
+ };
+
+ return (
+
+
useUnsavedFormChanges Example
+
+ {isFormChanged &&
You have unsaved changes!
}
+
+ );
+}
+
+export default App;
+
+```
+
+## Hook
+
+```tsx
+
+import { useEffect, useState } from 'react';
+
+export function useUnsavedFormChanges() {
+ const [isFormChanged, setIsFormChanged] = useState(false);
+
+ const setFormChanged = (value: boolean) => {
+ setIsFormChanged(value);
+ };
+
+ useEffect(() => {
+ const handleBeforeUnload = (event: { returnValue: string }) => {
+ if (isFormChanged) {
+ const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
+ event.returnValue = confirmationMessage;
+ return confirmationMessage;
+ }
+ };
+
+ window.addEventListener('beforeunload', handleBeforeUnload);
+
+ return () => {
+ window.removeEventListener('beforeunload', handleBeforeUnload);
+ };
+ }, [isFormChanged]);
+
+ return { isFormChanged, setFormChanged };
+}
+
+```
+
+## API
+
+Returns
+
+| Name | Type | Description |
+| ---- | ---- | ----------- |
+| `isFormChanged` | `boolean` | Indicates whether the form has unsaved changes. |
+| `setFormChanged` | `(value: boolean) => void` | A function to set the `isFormChanged` state. |
+
diff --git a/theme.config.jsx b/theme.config.jsx
index b40e2c1..61a0a08 100644
--- a/theme.config.jsx
+++ b/theme.config.jsx
@@ -76,6 +76,7 @@ const config = {
title === "useUrl" ||
title === "useEnv" ||
title === "useMouse" ||
+ title === "useUnsavedFormChanges" ||
title === "useCookie") && (
New