React - form with useState example (controlled components)

8 points
Created by:
Dirask Community

In this article we would like to show you how to use React forms with useState hook.

Below example shows how to make a form as an functional controlled component.
It's a simple form with two inputs: username, password and submit button.

With useState we are able to keep the data in component's state - in our case it's username and password. When onChange event occurs then setUsername and setPassword update the state.

Quick solution:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const Form = () => {
    const [username, setUsername] = React.useState();
    const [password, setPassword] = React.useState();
    const handleSubmit = e => {
        const data = {
          username, password
        const json = JSON.stringify(data, null, 4);
    return (
      <form onSubmit={handleSubmit}>
          <label>Username: </label>
          <input type="text" value={username}
            onChange={e => setUsername(} />
          <label>Password: </label>
          <input type="password" value={password}
            onChange={e => setPassword(} />
        <button type="submit">Submit</button>

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );

Important note:

When you create forms, React recommends using uncontrolled components,
because with controlled components large amount of input elements with onChange event handling leads to performance degradation by component multiple re-rendering.

Read this article to see uncontrolled version.

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé