How to use the useLocalStorage hook for persistent form data in Next.js



Image not found!!

To use the useLocalStorage hook for persistent form data in a Next.js application, you can follow these steps:

  1. Install the use-local-storage package if you haven't already:

    bash
    npm install use-local-storage

    or

    bash
    yarn add use-local-storage
  2. Create a custom hook that utilizes the useLocalStorage hook to handle form data:

    jsx
    // utils/useForm.js import { useState } from 'react'; import useLocalStorage from 'use-local-storage'; const useForm = (initialValues, storageKey) => { const [formData, setFormData] = useLocalStorage(storageKey, initialValues); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; const resetForm = () => { setFormData(initialValues); }; return { formData, handleChange, resetForm }; }; export default useForm;
  3. Use the custom hook in your Next.js component:

    jsx
    // pages/index.js import { useState } from 'react'; import useForm from '../utils/useForm'; const HomePage = () => { const initialValues = { // your form fields and their initial values firstName: '', lastName: '', // ... }; const storageKey = 'formData'; // choose a unique key for local storage const { formData, handleChange, resetForm } = useForm(initialValues, storageKey); const handleSubmit = (e) => { e.preventDefault(); // Handle form submission logic console.log('Form submitted:', formData); }; return ( <div> <form onSubmit={handleSubmit}> {/* Your form fields */} <label> First Name: <input type="text" name="firstName" value={formData.firstName} onChange={handleChange} /> </label> <label> Last Name: <input type="text" name="lastName" value={formData.lastName} onChange={handleChange} /> </label> {/* ... other form fields */} <button type="submit">Submit</button> <button type="button" onClick={resetForm}> Reset </button> </form> </div> ); }; export default HomePage;

    In this example, the useForm custom hook takes initial values and a storage key as parameters. It uses the useLocalStorage hook to manage the form data in local storage. The component then uses the returned formData, handleChange, and resetForm functions to handle the form state.

Remember to customize the form fields and their initial values according to your application's requirements.