Creating Reusable Logic (e.g., Form Handling)
0 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
/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