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 deepFreeze(obj) { const propNames = Reflect.ownKeys(obj); for (const name of propNames) {
Recursively freezing a nested object
recursion
immutability
object-freezing
Intermediate
6 steps
javascript
class InfiniteScroll { constructor(sentinel, { loadMore, root = null, rootMargin = '200px' } = {}) { this.sentinel = sentinel; this.loadMore = loadMore;
Infinite scroll with IntersectionObserver
intersectionobserver
pagination
async
Intermediate
10 steps
javascript
import { forwardRef, useImperativeHandle, useRef, useState } from 'react'; const TextField = forwardRef(function TextField( { label, error, onChange, ...props },
Exposing an imperative handle in React
forwardref
useimperativehandle
refs
Advanced
8 steps
typescript
import { useState, useCallback } from 'react'; type Todo = { id: string;
Optimistic UI updates in a React hook
optimistic-updates
custom-hooks
error-handling
Intermediate
8 steps
javascript
import { NextResponse } from 'next/server'; import { createWriteStream } from 'node:fs'; import { mkdir } from 'node:fs/promises'; import { pipeline } from 'node:stream/promises';
Streaming file uploads in a Next.js route
file-upload
streams
validation
Intermediate
9 steps
javascript
const crypto = require('crypto'); function inMemoryCache({ maxAge = 60_000, maxEntries = 500 } = {}) { const store = new Map();
Building an in-memory cache middleware in Express
caching
middleware
etag
Advanced
10 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.