cod;nncode. learn. thrive.

Create a 'useFormInput' Custom Hook in React

Create a 'useFormInput' Custom Hook in React

Posted Sep 24, 2023

Hey there! Today, we're diving into the magical world of React hooks with a hilarious twist.

We'll create a super-useful custom hook called 'useFormInput' that'll make handling forms as easy as pie 🥧 (without any of the mess, of course).

We'll be whipping up a project with at least three inputs, both with and without our fancy hook.

What's the Deal with 'useFormInput'?

Imagine a world where dealing with form inputs is as smooth as butter. That's precisely what our 'useFormInput' custom hook does! It's like having a personal form assistant who handles all the nitty-gritty form stuff for you.

Hook It Up: Creating 'useFormInput'

import { useState } from "react";

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  const handleChange = (e) => {

  return {
    onChange: handleChange,

export default useFormInput;

We've got our secret sauce ready! This hook gives us a 'value' and an 'onChange' function, making our lives easier.

The "No Hook" Scenario

Before we unveil the full magic of 'useFormInput', let's see how we'd handle our form inputs without it. Brace yourselves; it's going to be a bit more "manual".

😓 Without the Hook

import React, { useState } from "react";

function NoHookForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
        onChange={(e) => setName(}
        onChange={(e) => setEmail(}
        onChange={(e) => setPassword(}
      {/* Add your form submit button here */}

Ugh, so many lines of code! 😫 Let's not put ourselves through this torture and dive into the hooky goodness instead.

The "Hooked" Scenario

😎 With the 'useFormInput' Hook

import React from "react";
import useFormInput from "./useFormInput";

function HookedForm() {
  const name = useFormInput("");
  const email = useFormInput("");
  const password = useFormInput("");

  return (
      <input type="text" placeholder="Name" {} />
      <input type="email" placeholder="Email" {} />
      <input type="password" placeholder="Password" {...password} />
      {/* Add your form submit button here */}

Putting It All Together

So there you have it! You've just mastered the art of using the 'useFormInput' custom hook to create neat and tidy forms with ease. Whether you're building the next big thing or just having some coding fun, this hook will save you loads of time and headaches.

Now, go forth and create those amazing React forms like a pro! 🚀 Happy coding!

Your feedback is our favorite notification! Share your thoughts about this page and make us smile.