useBeforeUnload

The useBeforeUnload hook is a custom hook provided by the "@remix-run/react" library. The primary use case for this hook is to prompt the user before they navigate away from a page or refresh it, ensuring that they don't lose unsaved changes or important data. You can also use this hook to save information to local storage or perform other cleanup tasks before the page unloads.

In this documentation, we'll walk through an example where users want to save information to local storage before a page unloads. We will create a LoaderFunction, ActionFunction, and a React component in the same file, and use the useBeforeUnload hook.

Dependencies

Before we start, make sure you have the following libraries imported:

import { Link, Form, useBeforeUnload } from "@remix-run/react";
import type { ActionFunction, LoaderFunction } from "@remix-run/server-runtime";
import { json } from "@remix-run/server-runtime";

Example: Saving Data to Local Storage Before Unloading

Let's create a simple form that allows users to input some text. We will use the useBeforeUnload hook to save the input to local storage before the page unloads.

LoaderFunction

First, let's define a LoaderFunction that retrieves the data from local storage when the page loads:

export const loader: LoaderFunction = async ({ request }) => {
  const formData = JSON.parse(localStorage.getItem("formData") || "{}");

  return json({ formData });
};

ActionFunction

Now, let's define an ActionFunction that handles form submissions and stores the data in local storage:

export const action: ActionFunction = async ({ request }) => {
  const formData = await request.formData();
  const data = Object.fromEntries(formData);

  // Do something with the data 

  return json(data);
};

React Component

Finally, let's create a React component that uses the useBeforeUnload hook to save the form data to local storage before the page unloads:

import { useLoaderData, redirect } from "@remix-run/react";

function FormComponent() {
  const data = useLoaderData();
  const [formData, setFormData] = React.useState(data.formData);

  useBeforeUnload((event) => {
    localStorage.setItem("formData", JSON.stringify(formData));
    event.preventDefault();
    event.returnValue = ""; // Required for some browsers
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  return (
    <Form method="post">
      <label htmlFor="inputField">Text:</label>
      <input
        id="inputField"
        type="text"
        name="inputField"
        value={formData.inputField || ""}
        onChange={handleChange}
      />
      <button type="submit">Save</button>
    </Form>
  );
}

Now, when users navigate away from the page or refresh it, the useBeforeUnload hook will save the form data to local storage, ensuring that their input is not lost.

Last updated