Building Controlled Forms with useState in React

Christina Kozanian
4 min readDec 5, 2023

--

Understanding State

In React, the term “state” refers to an object that represents the internal data of a component. A change of state means the component will re-render with the current value held in state.

React provides a powerful and flexible way to manage state. In assessing which elements of an application should be defined using state, the question we should be asking is “Will this value change as the application is in use?” If the answer is yes, state will most likely be your answer. One common use of state is handling forms, where user input needs to be captured and processed. In this article, we’ll explore how to set up a controlled form using the useState hook in React.

Understanding Controlled Forms

A controlled form refers to a form whose state is controlled by React components. Instead of letting the DOM handle the form’s state, React components manage and control the form data internally. This allows for more dynamic and interactive forms.

As we walk through the steps below, consider coding along in a React template on Replit to help visualize each step.

Step 1: Creating a Form Component

Let’s start with creating a new component for your form. In your src directory, create a file named FormComponent.js and define a simple functional component:

Now, let’s introduce state to the form. We’ll use the useState hook to manage the form data.

We must first import useState at the top of the FormComponent.js file. The useState hook is used to declare and set the initial state of state variables. It returns an array with two elements:

  1. The current state value.
  2. A function that allows you to update the state.

When you use the “const” statement to declare a state variable, you are typically using array destructuring to assign names to these elements.

Here's the basic syntax:

const [stateValue, setStateFunction] = useState(initialState);
  • stateValue: Represents the current state value.
  • setStateFunction: A function that updates the state.
  • initialState: Represents the initial value held in state.

Here, we initialize both username and password as empty strings. The setUsername and setPassword function will be used to update this state when inputs are added by the user.

Step 2: Handling Form Input Changes

In order to make the form controlled, we need to capture the changes being entered in the input fields. In the code below, we’ll fill in the form content that will be rendered by the FormComponent.

We’ll need to include input elements with onChange event handlers that update state using the state functions we defined earlier. We also need to set the input values to each corresponding state variable:

For further clarity, the onChange function in the username input tag captures the value of the event, which in this case is a string. The setUsername function internally and dynamically sets what is being entered into the input field as the variable username. This is why we set the value of the input tag to the username variable.

Step 3: Handling Form Submission

Next, let’s handle the form submission. We’ll add a submit button and an onSubmit event handler for the form:

The onSubmit event of the form triggers the handleSubmit function, preventing the default form submission and allowing you to handle it manually. In this example, we log the data from the form to the console, but you can replace this with your desired submission logic.

Step 4: Using the FormComponent

Now that our FormComponent is ready, let’s use it in the src/App.js file:

Make sure to save your changes and start the server by running “npm start” in your terminal. Don’t forget to import the FormComponent file from the proper route!

Your browser should pop open to this link http://localhost:3000 where you will be able to see the controlled form in action. Try entering values into the input fields and submitting the form to observe the logged output. You now have the power to use the values held in state in any way you like with the flexibility to change them!

In this tutorial, we’ve walked through the process of setting up a controlled form using the useState hook in React. By managing the form state within the component, you gain more control over the form’s behavior and can easily implement features like form validation, dynamic updates, and interactions. This approach enhances the overall user experience and sets the foundation for building more sophisticated forms in your React applications. Try to experiment with different form elements and submission logic to customize the controlled form according to your application’s needs. Have fun exploring and keep it controlled!

--

--

Christina Kozanian
Christina Kozanian

Written by Christina Kozanian

0 Followers

Experienced programmer in Python and JavaScript frameworks like Flask and React, coupled with a unique blend of technical acumen and artistic insight.

No responses yet