Creating Reusable Logic (e.g., Form Handling)
0 621
🔠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 useuseForm 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
/hooksfolder - ✅ 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!
Share:




Comments
Waiting for your comments