Creating Reusable Logic (e.g., Form Handling)
×


Creating Reusable Logic (e.g., Form Handling)

453

๐Ÿ” Why Reusable Logic Matters

When building React apps, you'll often face scenarios like form validation, input management, or toggling UI components โ€” again and again. โœ๏ธ Writing the same logic in multiple components is not only repetitive, but also error-prone. Thatโ€™s where creating reusable logic using Custom Hooks comes in handy. ๐Ÿ’ก

๐Ÿงฐ Reusable Logic via Custom Hooks

Custom hooks are the perfect way to extract shared logic into isolated, testable, and composable pieces. Letโ€™s take a practical example: a **form handling hook** that manages inputs, resets, and submissions โ€” all in one.

๐Ÿ“‹ Basic Form Handling Logic

Letโ€™s say we have a form with name and email fields. Hereโ€™s how we might build a hook to handle it:


// useForm.js
import { useState } from 'react';

function useForm(initialValues, onSubmit) {
  const [values, setValues] = useState(initialValues);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(values);
  };

  const resetForm = () => setValues(initialValues);

  return {
    values,
    handleChange,
    handleSubmit,
    resetForm
  };
}

export default useForm;

๐Ÿงช How to Use the Form Hook

Hereโ€™s how you can use useForm inside any component:


import useForm from './useForm';

function ContactForm() {
  const { values, handleChange, handleSubmit, resetForm } = useForm(
    { name: '', email: '' },
    (formValues) => {
      console.log('Submitted:', formValues);
      resetForm();
    }
  );

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="name"
        value={values.name}
        onChange={handleChange}
        placeholder="Name"
      />
      <input
        name="email"
        value={values.email}
        onChange={handleChange}
        placeholder="Email"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

๐ŸŽฏ This is reusable โ€” works for any form, any number of fields.

๐Ÿง  Add Validation (Optional)

You can enhance the hook with inline validation too:


function useForm(initialValues, onSubmit, validate) {
  const [values, setValues] = useState(initialValues);
  const [errors, setErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setValues((prev) => ({ ...prev, [name]: value }));

    if (validate) {
      const newErrors = validate({ ...values, [name]: value });
      setErrors(newErrors);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const newErrors = validate ? validate(values) : {};
    if (Object.keys(newErrors).length === 0) {
      onSubmit(values);
    } else {
      setErrors(newErrors);
    }
  };

  return { values, errors, handleChange, handleSubmit };
}

Now your forms can use custom validation logic, too! ๐Ÿšฆ

๐Ÿ“ฆ Other Examples of Reusable Logic

  • ๐Ÿ“Š usePagination โ€“ handle page switching, limits, and counts
  • ๐ŸŽš๏ธ useToggle โ€“ toggle a boolean value (e.g., modal open/close)
  • ๐Ÿ” useDebounce โ€“ delay input value updates (e.g., search)
  • ๐Ÿ•’ useTimer โ€“ manage countdowns or intervals

๐Ÿ“ Organizing Custom Hooks

To keep your project clean:

  • ๐Ÿ“ Put custom hooks in a /hooks folder
  • โœ… Name them consistently (e.g., useForm, useModal)
  • ๐Ÿงช Consider unit-testing them separately

๐Ÿš€ Final Thoughts

Reusable logic โ€” especially with custom hooks โ€” is the backbone of scalable React applications. Whether itโ€™s form handling, toggles, pagination, or async requests, extracting logic into clean, reusable functions makes your code DRY, maintainable, and professional. ๐Ÿง ๐Ÿ”



If youโ€™re passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ€“ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat