React useUnsaved Hook

import React, { useEffect, useState } from “react”;
import { Prompt } from “react-router-dom”;
const useUnsaved = (message = “Do you want to leave”) => {
const [isDirty, setIsDirty] = useState(false);
useEffect(() => {
window.onbeforeunload = isDirty && (() => message);
return () => (window.onbeforeunload = null);
}, []);
const prompt = <Prompt when={isDirty} message={message} />; return [prompt, () => setIsDirty(true), () => setIsDirty(false)];};export default useUnsaved;

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Thilina Dilshan
Thilina Dilshan

Written by Thilina Dilshan

Software developer , love to learn

No responses yet

Write a response