• Post category:React
  • Reading time:4 mins read

Handling form validation in React can be a bit tricky, but with the useReducer hook, it becomes much more manageable and elegant. In this post, we’ll explore how to use useReducer to handle form state and validation, making your forms robust and easy to maintain.

What is useReducer?

The useReducer hook is a React hook that is used for state management. It’s an alternative to useState and is usually preferred when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

Setting Up the Reducer

First, we need to set up our reducer. A reducer is a function that takes the current state and an action, then returns a new state.

const formReducer = (state, action) => {
  switch (action.type) {
    case 'INPUT_CHANGE':
      return {
        [action.field]: action.value,
        errors: {
          [action.field]: action.error,
    case 'SUBMIT':
      const errors = validate(state);
      return { ...state, errors };
      return state;

Initial State and Validation Function

Let’s define our initial state and a simple validation function.

const initialState = {
  username: '',
  email: '',
  errors: {},

const validate = (state) => {
  const errors = {};
  if (!state.username) errors.username = 'Username is required';
  if (!state.email) errors.email = 'Email is required';
  return errors;

Implementing the useReducer Hook

Now, let’s implement the useReducer hook in our form component.

const FormWithReducer = () => {
  const [state, dispatch] = useReducer(formReducer, initialState);

  const handleChange = (e) => {
    const { name, value } = e.target;
      type: 'INPUT_CHANGE',
      field: name,
      error: validate({ ...state, [name]: value })[name],

  const handleSubmit = (e) => {
    dispatch({ type: 'SUBMIT' });
    const errors = validate(state);
    if (Object.keys(errors).length === 0) {
      console.log('Form submitted successfully', state);

  return (
    <form onSubmit={handleSubmit}>
        {state.errors.username && <p>{state.errors.username}</p>}
        {state.errors.email && <p>{state.errors.email}</p>}
      <button type="submit">Submit</button>


Using the useReducer hook for form validation in React helps in managing complex form state logic more effectively. It allows you to handle form data and validation in a cleaner and more structured way. Give it a try in your next React project!

Leave a Reply