Notes > useForm


If you’ve been doing ReactJS for some time you know that it’s a lot of work just to do <Forms /> in React. There’s just too much stuff you have to do and consider. You have to do your own state management for the inputs else it’ll not work.

Here’s how I do it useForm method/hooks for creating Forms and this is my go-to custom hook for my forms.

import { useState, useEffect } from 'react';

export default function useForm(initial = {}) {
  // create a state object for our inputs
  const [inputs, setInputs] = useState(initial);

  const initialValue = Object.values(initial).join('');

  useEffect(() => {
    // this function runs when the things we are watching change
  }, [initialValue]);

  function handleChange(e) {
    let { value, name, type } =;
    if (type === 'number') {
      value = parseInt(value);
    if (type === 'file') {
      [value] =;
    if (type === 'checkbox') {
      const { checked } =;
      value = checked;
      // copy the existing state
      [name]: value,

  function resetForm() {

  function clearForm() {
    const blankState = Object.fromEntries(
      Object.entries(inputs).map(([key, value]) => [key, ''])

  // return the thins we want to surface from this custom hook
  return { inputs, handleChange, resetForm, clearForm };

How will I use this on my form component? you just have to import the custom hook useForm , then pass initial data values.

const {inputs, handleChange} = useForm({ 
//add your initial values. you set it blank be blank as initial value too!
  name: 'Owa',
  age: 21,
  isCool: true,
	<input type="textbox" name="name" onChange={handleChange} />
	<input type="number" name="age" onChange={handleChange} />
👌Found this great library to use react-use-forms for much more complex forms that you need to build. Documentation is solid and easy to use. 👍

Tags 🏷

  • ReactJs