#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Forms (React)

Working with Custom Hooks

A custom hook is a JavaScript function whose name starts with use and which calls other hooks such as useState or useEffect. It lets you pull repeated stateful logic out of components and reuse it. In forms, the classic example is an input hook that tracks a field's value, whether it has been touched, and whether it is valid, so every field in every form does not need the same ten lines of code.

Spotting logic worth extracting

After adding validation in the previous lesson, a form with an email and a name field probably has duplicate code: two pieces of value state, two "touched" flags, two change handlers, two blur handlers and two validity checks. The only real difference between the fields is the validation rule. That is exactly the situation a custom hook solves: same behaviour, different configuration.

Writing a useInput hook

import { useState } from 'react';

export function useInput(validate) {
  const [value, setValue] = useState('');
  const [touched, setTouched] = useState(false);

  const isValid = validate(value);
  const hasError = touched && !isValid;

  return {
    value,
    isValid,
    hasError,
    onChange: (e) => setValue(e.target.value),
    onBlur: () => setTouched(true),
    reset: () => {
      setValue('');
      setTouched(false);
    },
  };
}

The hook receives a validation function as a parameter, keeps its own state, derives isValid and hasError on every render, and returns everything the component needs.

Notice that isValid is not stored in state. It is calculated from value each time the component renders. Storing derived values in separate state variables is a common source of bugs, because the two can drift out of sync. Computing them keeps a single source of truth. The touched flag exists so errors appear only after the user has left the field, rather than the moment the page loads.

Using the hook in a form

function SignupForm() {
  const name = useInput((v) => v.trim() !== '');
  const email = useInput((v) => /^\S+@\S+\.\S+$/.test(v));

  const formIsValid = name.isValid && email.isValid;

  function handleSubmit(e) {
    e.preventDefault();
    if (!formIsValid) return;
    console.log({ name: name.value, email: email.value });
    name.reset();
    email.reset();
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={name.value} onChange={name.onChange} onBlur={name.onBlur} />
      {name.hasError && <p>Please enter your name.</p>}

      <input value={email.value} onChange={email.onChange} onBlur={email.onBlur} />
      {email.hasError && <p>Please enter a valid email.</p>}

      <button disabled={!formIsValid}>Sign up</button>
    </form>
  );
}

Adding a third field is now one line plus its markup. If you later decide errors should appear only after the first submit, you change the hook once and every field follows.

A misunderstanding to clear up early

Custom hooks share logic, not state. Each call to useInput creates a completely separate set of state variables. The name and email fields above do not affect each other, and two components using the same hook do not see each other's values. If you actually need shared data across components, use context or lift the state up to a common parent.

Custom hooks also follow the rules of hooks. Call them at the top level of a component or another hook, never inside an if, a loop or an event handler. React relies on hooks being called in the same order on every render. The use prefix is what lets the linter check these rules for you, so do not drop it.

Design tips

  • Return an object when there are many values, so callers can pick what they need by name.
  • Accept configuration, like the validation function, as parameters instead of hard-coding rules.
  • Keep the hook free of JSX; it handles behaviour, while components handle markup.
  • Keep hooks in their own files, often in a hooks folder.

The result is form components that read like a description of the fields, with the mechanics tucked away in one tested function.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course