A Simple Custom Hook in React.js

Yogesh KanwadeYogesh Kanwade
1 min read

Let’s try a simple custom hook that can be used to handle form values.

import { useState } from 'react';

const useFormValues = (initialFormValues) => {
  const [formValues, setFormValues] = useState(initialFormValues);

  const setFormValueByKey = (field, newValue) => {
    setFormValues((prev) => ({ ...prev, [field]: newValue }));
  };

  return [formValues, setFormValueByKey];
};
💡
setFormValueByKey is a closure because it "closes over" the setFormValues function from its parent scope. It remembers a reference to this setFormValues function.

Usage:

const MyComponent = () => {
  const [formValues, setFormValueByKey] = useFormValues({ name: '', age: 0 });

  return (
    <>
      <h1>Name: {formValues.name}</h1>
      <input
        type="text"
        name="name"
        value={formValues.name}
        onChange={(e) => setFormValueByKey('name', e.target.value)}
      />
    </>
  );
};

A generic handler for updating form values:

const handleChange = (e) => {
  const { name, value } = e.target;
  setFormValueByKey(name, value);
}:

<input name="name" value={formValues.name} onChange={handleChange} />
<input name="age" value={formValues.age} onChange={handleChange} />

Type Safe version:

type FormValueSetter<T> = <K extends keyof T>(field: K, value: T[K]) => void;

const useFormValues = <T extends Record<string, any>>(initialFormValues: T): [T, FormValuesSetter<T>] => {
    const setFormValueByKey: FormValuesSetter<T> = (field, newValue) => {}
}

And that’s how we have our own custom hook in ReactJS !

💡
1
Subscribe to my newsletter

Read articles from Yogesh Kanwade directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yogesh Kanwade
Yogesh Kanwade

I'm Yogesh Kanwade, a final year Computer Engineering student with a deep passion for software development. I am a continuous learner, with hardworking and goal-driven mindset and strong leadership capabilities. I am actively exploring the vast possibilities of Web Development along with AWS and DevOps, fascinated by their impact on scalable and efficient web solutions.