How to Implement an Auto-Save Feature in React?
In modern web applications, more and more inputs are adopting an auto-save system. This trend is particularly noticeable since tools like Notion introduced an innovative editing experience where changes are seamlessly saved as you type, without requiring a manual "Save" button. In this article, we'll explore how to implement a similar auto-save feature in React.
What is an Auto-Save System?
Auto-save allows for changes in inputs or settings to be saved automatically, without the user needing to click a "Save" button each time they make an adjustment. For example, instead of requiring users to confirm their changes with a button click, an auto-save system tracks when an input is modified and then initiates a save request to the server automatically.
However, since users don’t actively confirm these saves, it's essential to provide feedback to let them know their changes were successfully saved. This can be achieved with a toast notification or an alert indicating that the save was successful.
Why Use Auto-Save?
Auto-save systems offer a smoother, more streamlined experience for users by reducing the number of clicks needed to save changes. They can be particularly helpful for settings pages or forms with multiple fields, as they eliminate the need for a save button on each component. Instead, changes are simply captured and saved automatically as users type.
Implementing Auto-Save in React: A Simple Example
To explain how to implement an auto-save feature, let’s take a simple example where a user can update their username and toggle whether they’d like to receive emails. Each change will be automatically saved without a save button, and the user will be notified when their changes are successfully saved.
Step 1: Basic Component Setup
We'll build a component called UserSettings
in React with TypeScript. This component will include:
- An input for the username.
- A checkbox to toggle email notifications.
- An auto-save function triggered when the user stops typing for a specified delay (e.g., 2.5 seconds).
Step 2: Creating the Auto-Save Logic
In our component, we’ll use the useState
and useEffect
hooks to monitor input changes and trigger a save after a debounce delay. Additionally, a toast notification will inform the user when the data is saved.
Here's how the component looks in code:
import { useEffect, useRef, useState } from "react"; import { useNotification } from "@/hooks/useNotifications"; function AutoSaveForm() { const notif = useNotification(); const timeoutRef = useRef<number | null>(null); const [name, setName] = useState(""); // Fonction pour sauvegarder les changements async function saveChange(updatedName: string) { try { // Simule l’appel à une API de sauvegarde console.log("Changes saved:", updatedName); notif.success({ title: "Saved", content: "Changes have been successfully saved!", }); } catch (e) { notif.error({ title: "Error", content: e.message, }); } } // Gère les changements de l'input avec un délai avant la sauvegarde function onNameChange(value: string) { setName(value); if (timeoutRef.current) { clearTimeout(timeoutRef.current); } // Déclenche la sauvegarde après un délai de 2,5 secondes timeoutRef.current = window.setTimeout(() => { saveChange(value); }, 2500); } return ( <div> <h1>Auto-Save Form</h1> <input type="text" placeholder="Enter your name" value={name} onChange={(e) => onNameChange(e.target.value)} /> </div> ); } export default AutoSaveForm;
Here we have a simple form with an input field for the user's name. The onNameChange
function is triggered whenever the input value changes. It updates the name
state and schedules a save operation after a delay of 2.5 seconds. The saveChange
function simulates an API call to save the changes and displays a notification to the user.
This is a optimitic save, if you want to save the data in the server, you can use the useEffect
hook to trigger the save operation when the component unmounts or when the name
state changes.