Collecting user inputs is a very important aspect of building a web application. You must follow certain rules when building apps with React.
React docs recommend to store users inputs in the state. This is not a requirement, but React ecosystem works more efficiently when you user inputs in the state. Components that follow this pattern are called controlled components because state has all the values and control over input elements.
Typically you set an onChange event handler on the input element, which updates the state every time user enters (or deletes) something in the field. In other words, every time there’s a change to value in the input field. Handler for the onChange event should call either setState() method or the updater function received from the useState() hook.
Advantages of storing user inputs in the state
React ecosystem is built around changes and quickly reflecting recent changes on the screen. One way React achieves this is by re-rendering the entire component tree when state values change. That’s why it’s important to tie inputs to the state. If you don’t, React will not know that there’s been a change and the page won’t be updated.
When building React applications, it’s also a good practice to have a ‘single source of truth’. For individual components, state is the single source of truth. You could come up with other ways to track changes and force a re-render, but it’s easier to follow recommendations of React.
In short, controlled components are necessary for consistency. It helps React components to stay in sync with the latest changes.
UX features for user inputs
You probably already know that collecting user inputs is extremely important. Naturally, you should make it easy for users to provide inputs. In addition to ease of use, you also need data to be accurate. With controlled components, it’s very easy to implement form validation to ensure consistency of data.
There are a number of libraries that can help you with validation, but you can also simply define a function that checks values in certain input fields before they are saved / submitted. You can even use conditional styling to highlight input fields that contain wrong values.
Another great feature is to clear form fields after submit. This is especially useful for forms that need to be submitted multiple times. With controlled components, you can simply reset state value to an empty string or null, and input value will be reset as well.
There are other features to enhance your input fields. For example, autocomplete so users won’t have to type too much. Most React developers use input elements from component libraries like Material UI. These libraries provide custom components with built-in features. You only need to set a custom prop and you’re good to go.
Top comments (0)