javascript
37 lines · 7 steps
Guarding unsaved changes with a React hook
A custom hook that warns users before they lose unsaved work, covering both browser navigation and in-app route changes.
Explained by
highlit
1import { useEffect, useRef } from "react";
2import { useBlocker } from "react-router-dom";
3
4export function useUnsavedChangesPrompt(isDirty, message = "You have unsaved changes. Leave anyway?") {
5 const messageRef = useRef(message);
6 messageRef.current = message;
7
8 useEffect(() => {
9 if (!isDirty) return;
10
11 const handleBeforeUnload = (event) => {
12 event.preventDefault();
13 event.returnValue = messageRef.current;
14 return messageRef.current;
15 };
16
17 window.addEventListener("beforeunload", handleBeforeUnload);
18 return () => window.removeEventListener("beforeunload", handleBeforeUnload);
19 }, [isDirty]);
20
21 const blocker = useBlocker(
22 ({ currentLocation, nextLocation }) =>
23 isDirty && currentLocation.pathname !== nextLocation.pathname
24 );
25
26 useEffect(() => {
27 if (blocker.state !== "blocked") return;
28
29 if (window.confirm(messageRef.current)) {
30 blocker.proceed();
31 } else {
32 blocker.reset();
33 }
34 }, [blocker]);
35
36 return blocker;
37}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A ref lets an effect read the latest prop value without re-subscribing every time it changes.
- 2Guarding unsaved work needs two mechanisms: the native beforeunload event for full page exits and a router blocker for SPA navigation.
- 3Always pair addEventListener with a cleanup function so effects don't leak stale handlers.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/guarding-unsaved-changes-with-a-react-hook-explained-javascript-8929/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.