React Create Form with useReducer React Hook Tutorial

In this guide, we will learn how to create a simple form in React application. We will show you how to use React Hooks to manage the state of the React form.

React is all about managing the state; in React components, data is maintained via the state.

Primarily, there are two types of components in React, one is a class component, and another is a functional component.

In the class component, we theoretically use state objects. On the other hand, for the functional component, we use hooks. In this article, we will discuss how to build a form in React, and we will use a functional component.

When you need to manage the simple state, you can do it with the useState hook. However, if more complex state management comes on your way, then React offers a useReducer hook.

The useReducer hook is best when you have to go through the complex state manipulations and state transitions.

The useReducer is a React hook function, and it takes a reducer function and an initial state.

const [state, dispatch] = useReducer(reducer, initialState);

This hook function returns an array with two values, and you can pass action and subsequently evoke it.

The reducer function returns data in the form of state. An action type usually invokes it. Ideally, an action orders the reducer about how to change the state.

Similarly, in this React hooks form example we will explain how to best used useReducer hook to create the form and how to manage the form state in React.

How to Build Simple Form in React using React Hook

  • Step 1: Create React App
  • Step 2: Build Component
  • Step 3: Create Form Component
  • Step 4: Update App Js
  • Step 5: Run Application

Create React App

Let’s be vigilant and start creating a brand new React application; we hope you have already installed the create-react-app CLI in your machine.

If so, go ahead and use the below command to create the blank React app.

npx create-react-app react-form

Next, get into the project folder.

cd react-form

Now, type the given command and execute to install the bootstrap library.

npm install bootstrap

Next, import the boostrap path from the node modules into the App.js file.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';

export default function App() {
  return (
    <>
      
    </>
  )
}

Build Component

To show you how to build a simple form in React, we need a separate component. Go to components/ directory, create RegisterUser.js file then add the provided command in the file.

import React from 'react'

export default function RegisterUser() {
  return (
    <div>
      
    </div>
  )
}

Create Form Component

The useReducer hook is all alone handling the form state since our form has four elements. We are managing every input’s value through one state management hook.

The useReducer hooks hold the current state and the new state; the current state is paired with the dispatchFormValue.

The reducerInputChange() function updates the previous form state to a new form state through the dispatchFormValue property.

Update code in components/form.component.js file:

import React, { useReducer } from 'react'

export default function RegisterUser() {
  const formInitialState = {
    firstName: '',
    lastName: '',
    email: '',
    password: '',
  }

  const [inputValues, dispatchFormValue] = useReducer(
    (curVal, newVal) => ({ ...curVal, ...newVal }),
    formInitialState,
  )

  const { firstName, lastName, email, password } = inputValues

  const reducerInputChange = (e) => {
    const { name, value } = e.target
    dispatchFormValue({ [name]: value })
    
    console.log(inputValues)
  }

  const onFormSubmit = (e) => {
    e.preventDefault()
    console.log(inputValues)
  }

  return (
    <div className="container mt-3">
      <form onSubmit={onFormSubmit} noValidate>
        <div className="form-group mb-3">
          <label className="mb-2">
            <strong>First name</strong>
          </label>
          <input
            required
            type="text"
            name="firstName"
            value={firstName}
            className="form-control"
            onChange={reducerInputChange}
          />
        </div>
        <div className="form-group mb-3">
          <label className="mb-2">
            <strong>Last name</strong>
          </label>
          <input
            type="text"
            name="lastName"
            value={lastName}
            className="form-control"
            onChange={reducerInputChange}
          />
        </div>
        <div className="form-group mb-3">
          <label className="mb-2">
            <strong>Email</strong>
          </label>
          <input
            type="text"
            name="email"
            value={email}
            className="form-control"
            onChange={reducerInputChange}
          />
        </div>
        <div className="form-group mb-3">
          <label className="mb-2">
            <strong>Password</strong>
          </label>
          <input
            type="text"
            name="password"
            value={password}
            className="form-control"
            onChange={reducerInputChange}
          />
        </div>
        <div className="d-grid">
          <button type="submit" className="btn btn-dark">
            Register
          </button>
        </div>
      </form>
    </div>
  )
}

Update App Js

The form component is ready, now this has to be added into the App.js component.

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css';
import RegisterUser from './components/RegisterUser'

export default function App() {
  return (
    <div>
      <RegisterUser />
    </div>
  )
}

Run Application

In this step, we will run the React application. Consequently, head over to terminal type and execute the suggested command.

npm start

React Create and Validate Form with React Hooks Tutorial

Summary

In this React form tutorial, we have learned how to create a form component in React. Also, we described how to use React hooks, to be more precise, the useReducer hook. We hope you have understood how to set and update the form state in React.