How to implement a custom hook for handling form reset in Next.js



Image not found!!


To implement a custom hook for handling form reset in Next.js, you can follow these general steps:

  1. Create a new file for your custom hook, for example, useFormReset.js.
jsx
// useFormReset.js import { useState } from 'react'; const useFormReset = () => { const [formState, setFormState] = useState({}); const resetForm = () => { setFormState({}); }; const handleChange = (fieldName, value) => { setFormState((prevFormState) => ({ ...prevFormState, [fieldName]: value, })); }; return { formState, handleChange, resetForm, }; }; export default useFormReset;
  1. Now, you can use this custom hook in your Next.js component.
jsx
// YourComponent.js import React from 'react'; import useFormReset from '../path/to/useFormReset'; const YourComponent = () => { const { formState, handleChange, resetForm } = useFormReset(); const handleSubmit = (e) => { e.preventDefault(); // Handle form submission with formState values console.log('Form submitted with:', formState); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={formState.name || ''} onChange={(e) => handleChange('name', e.target.value)} /> </label> <br /> <label> Email: <input type="email" value={formState.email || ''} onChange={(e) => handleChange('email', e.target.value)} /> </label> <br /> <button type="submit">Submit</button> <button type="button" onClick={resetForm}> Reset </button> </form> ); }; export default YourComponent;

Now, you can use the YourComponent in your Next.js pages, and it will have the form reset functionality through the resetForm function provided by the custom hook.