Skip to main content
← Back to Blog
2026-02-21 · 8 min readWeb DevelopmentUpdated Oct 29, 2026

Mastering React Hooks: From useState to Building a Production-Ready Custom Hook

A step-by-step guide to React custom hooks. You start with useState and the cases where you don't need useEffect, then pull repeated form logic out of a login form into a useForm hook that tracks values, shows errors after the first submit and disables the button while your submit function runs. The code was run with React 19 and React Testing Library.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
8 views
Mastering React Hooks: From useState to Building a Production-Ready Custom Hook

Every form in a React app needs the same plumbing: hold the values, update them on each keystroke, check them on submit and block double clicks. This guide is for developers who know useState and want to stop copying that plumbing between forms. You'll group related state, see where useEffect isn't needed, and then pull the form logic into a useForm custom hook that you can reuse in any form.

This is part 20 of the Frontend & JavaScript Fundamentals series. It follows state and props in class and function components, so you should already be comfortable with useState.

Key takeaways

  • Keep fields that change together in one state object, and update it with a copy, never by mutation.
  • If a value can be worked out from state, such as validation errors, calculate it during render instead of syncing it with an effect.
  • A custom hook shares stateful logic, not state: each form that calls useForm gets its own values.

Why hooks changed how logic is shared

Hooks arrived in React 16.8. Before that, shared behavior lived in higher-order components and render props. The old React docs describe the result as a "wrapper hell" of nested components in DevTools. Hooks let a plain function hold that logic instead.

A custom hook is a JavaScript function whose name starts with use and a capital letter, and that calls other hooks. That's the rule from the React docs. The name tells you, and the linter, that state or effects may be inside.

Group state that changes together

The React docs give a simple rule: if two or more state variables always update at the same time, consider merging them into one. A form's fields are a good example. You update one record, not three unrelated strings.

// Three separate variables for one record
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

// One object for the whole form
const [formData, setFormData] = useState({
  username: '',
  email: '',
  password: '',
});

There is one catch with object state. React treats state as read-only, so you replace the object instead of changing it. Copy the other fields with spread syntax, or they disappear.

// Wrong: mutation, React ignores it
formData.email = 'a@b.co';

// Wrong: drops username and password
setFormData({ email: 'a@b.co' });

// Right: copy, then override one field
setFormData((prev) => ({ ...prev, email: 'a@b.co' }));

The last line passes an updater function. The useState reference explains that React queues updaters and runs each one with the latest state. That matters when several updates happen in one event.

You might not need an effect

useEffect lets a component sync with something outside React, such as the network or a browser API. The React docs say that if no external system is involved, you shouldn't need an effect. Two common cases:

  • Values you can calculate. A filtered list or a full name comes from state you already have. Compute it during render.
  • Things a user did. A form submit belongs in the submit handler, because by the time an effect runs you no longer know what the user did.
// Avoid: extra state plus an effect to keep it in sync
const [fullName, setFullName] = useState('');
useEffect(() => {
  setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);

// Better: calculated during render
const fullName = firstName + ' ' + lastName;

This idea shapes the hook below. Validation errors are a value you can calculate from the form's values, so the hook won't store them in an effect.

The problem: form logic tied to one form

Start with a validation function. It takes the values and returns an object with one message per broken field. An empty object means the form is valid.

export function validateLogin(values) {
  const errors = {};
  if (!values.email.includes('@')) errors.email = 'Enter a valid email.';
  if (values.password.length < 8) errors.password = 'Use at least 8 characters.';
  return errors;
}

Here is a login form that handles everything inline.

import { useState } from 'react';
import { validateLogin } from './validateLogin';

export function LoginForm({ onLogin }) {
  const [values, setValues] = useState({ email: '', password: '' });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  function handleChange(e) {
    setValues({ ...values, [e.target.name]: e.target.value });
  }

  async function handleSubmit(e) {
    e.preventDefault();
    const nextErrors = validateLogin(values);
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) return;

    setIsSubmitting(true);
    try {
      await onLogin(values);
    } finally {
      setIsSubmitting(false);
    }
  }

  return <form onSubmit={handleSubmit}>{/* inputs, errors and button */}</form>;
}

It works. But handleChange, handleSubmit and the three state variables say nothing about logins. A contact form or a signup form needs the same code. Also, the errors stay on screen after the user fixes a field, until the next submit.

Build the useForm hook

The hook takes two things: the starting values and a validation function. It returns the current values, the errors, a submitting flag and two handlers.

import { useState, useCallback } from 'react';

export function useForm(initialValues, validate) {
  const [values, setValues] = useState(initialValues);
  const [submitted, setSubmitted] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Derived during render: no effect, no second errors state to keep in sync
  const errors = submitted ? validate(values) : {};

  const handleChange = useCallback((e) => {
    const { name, value } = e.target;
    setValues((prev) => ({ ...prev, [name]: value }));
  }, []);

  function handleSubmit(onSubmit) {
    return async (e) => {
      e.preventDefault();
      setSubmitted(true);
      if (Object.keys(validate(values)).length > 0) return;

      setIsSubmitting(true);
      try {
        await onSubmit(values);
      } finally {
        setIsSubmitting(false);
      }
    };
  }

  return { values, errors, isSubmitting, handleChange, handleSubmit };
}

Checked against react@19.3.1, @testing-library/react@16.3.3 and jest@30.5.2, 2026-10-29.

Here is what each part does:

  • values holds every field in one object. handleChange reads the input's name attribute, so one handler serves every field.
  • errors is not state. Once the user has tried to submit, the hook runs validate on every render. Fix a field and its message goes away on the next keystroke.
  • handleSubmit(onSubmit) returns the real submit handler. It stops the browser's own submit, checks the values and only then awaits your function. The finally block turns the flag off even if your function throws.

Where useCallback helps, and where it doesn't

handleChange is wrapped in useCallback, so it stays the same function between renders. The React docs say that only pays off in two cases: when you pass the function to a child wrapped in memo, or when another hook lists it as a dependency. They also say to treat useCallback as a performance tool only. If your code breaks without it, fix the real bug first.

handleSubmit is left as a plain function. Each call to handleSubmit(onLogin) creates a new handler anyway, so caching the outer function would buy nothing. If your project uses React Compiler, the docs note that it memoizes functions for you.

Use the hook in the form

The login form now only describes what it shows.

import { useForm } from './useForm';
import { validateLogin } from './validateLogin';

export function LoginForm({ onLogin }) {
  const { values, errors, isSubmitting, handleChange, handleSubmit } = useForm(
    { email: '', password: '' },
    validateLogin
  );

  return (
    <form onSubmit={handleSubmit(onLogin)} noValidate>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" value={values.email} onChange={handleChange} />
      {errors.email && <p role="alert">{errors.email}</p>}

      <label htmlFor="password">Password</label>
      <input id="password" name="password" type="password" value={values.password} onChange={handleChange} />
      {errors.password && <p role="alert">{errors.password}</p>}

      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Logging in…' : 'Log in'}
      </button>
    </form>
  );
}

MDN describes novalidate as telling the browser not to validate the form on submit, so your own messages show instead of the browser's. Each input has a <label>, which screen readers need and tests can use to find the field. A contact form would call useForm with its own fields and its own validation function. The React docs point out that each call to a hook is independent, so two forms never share values.

onLogin is yours to write, for example a fetch call to your API. Catch its errors inside it and show a message, because the hook only resets the submitting flag.

Fixed in this version

The earlier version of this hook never called the submit function, didn't return isSubmitting, and used an effect with missing dependencies to re-check errors. The version above calls your function, returns the flag, and calculates errors during render.

This test, written with React Testing Library, checks that behavior: errors appear on an empty submit, clear as you type, and the button is disabled while the submit runs. The Jest and React Testing Library guide shows how to set it up.

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { LoginForm } from './LoginForm';

test('blocks submit with errors, clears them as the user types, then submits', async () => {
  const user = userEvent.setup();
  let resolve;
  const onLogin = jest.fn(() => new Promise((r) => { resolve = r; }));
  render(<LoginForm onLogin={onLogin} />);

  await user.click(screen.getByRole('button', { name: 'Log in' }));
  expect(screen.getAllByRole('alert')).toHaveLength(2);
  expect(onLogin).not.toHaveBeenCalled();

  await user.type(screen.getByLabelText('Email'), 'a@b.co');
  expect(screen.getAllByRole('alert')).toHaveLength(1);
  await user.type(screen.getByLabelText('Password'), 'longenough');
  expect(screen.queryByRole('alert')).not.toBeInTheDocument();

  await user.click(screen.getByRole('button', { name: 'Log in' }));
  expect(onLogin).toHaveBeenCalledWith({ email: 'a@b.co', password: 'longenough' });
  expect(screen.getByRole('button', { name: 'Logging in…' })).toBeDisabled();
  resolve();
  expect(await screen.findByRole('button', { name: 'Log in' })).toBeEnabled();
});

When a custom hook is worth it

A production form usually needs more than this hook gives you: a reset after success, per-field "touched" state so errors appear only after a user leaves a field, and async checks such as "is this email taken?". A form library covers those cases.

Option What it gives you Trade-off Use it when
Inline state in the component Everything visible in one place Copied into every form One small form
A custom hook such as useForm Shared logic, separate state per form One more file to learn Several forms with the same flow
A form library Field arrays, schema validation, many edge cases A dependency and its API Large or complex forms

The React docs warn against extracting a hook for every bit of duplication. Wrapping a single useState call, for example, is probably unnecessary. Their advice is to keep custom hooks focused on a concrete use case, with a name that says what it does.

Next in the series, Context API vs Redux covers the case useForm doesn't: state that many components need to share.

Frequently asked questions

What makes a function a custom hook?

It's a function whose name starts with use plus a capital letter, and it calls other hooks inside. The React docs say functions that don't call hooks shouldn't use the use prefix. The prefix tells readers and the linter that the rules of hooks apply.

Do two components that call the same custom hook share state?

No. The React docs state that custom hooks share stateful logic, not state. Each call gets its own state. To share the actual values, lift the state up to a common parent or use context.

Why not store validation errors in state with useEffect?

Errors can be calculated from the current values, so storing them twice means keeping two copies in sync. The React docs recommend calculating such values during render. It's simpler, and it avoids an extra render each time the values change.

Should I wrap every handler in useCallback?

No. The React docs say it only helps when the function goes to a memo child or into a hook's dependency list. In other cases there's no benefit. React Compiler can also handle this memoization for you.

When should I use a form library instead?

As a rule of thumb, reach for one when you need dynamic field lists, schema validation or many forms with complex rules. A small hook like useForm covers simple forms well. It's also a good way to learn what those libraries do for you.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. React docs: Reusing Logic with Custom Hooks
  2. React docs: Choosing the State Structure
  3. React docs: useState
  4. React docs: You Might Not Need an Effect
  5. React docs: useCallback
  6. MDN: The form element (novalidate)
  7. React (legacy docs): Introducing Hooks
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.