Hello Sunil
controlled-vs-uncontrolled-components-react-feature-image

Controlled vs. Uncontrolled Components in React: A Quick Guide

When building forms in React, managing input fields efficiently is crucial. Two common approaches to handling input data are using Controlled Components and Uncontrolled Components. Let’s break down what these components are, how they work, and when to use each.

A Controlled Component in React is a component where React controls the input elements, meaning the component’s state handles the input value. With this approach, React keeps track of every keystroke in the input field, which allows for precise control and validation as the user types.

ControlledInput.js

"use client"
import React, {useState} from 'react'

const ControlledInput = () => {
	const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };
	return (
		<div>
      <label>
        Name:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <p>Current Value: {value}</p>
    </div>
	)
}

export default ControlledInput

In this example:

  • value is a state variable that holds the input’s current value.
  • onChange handler updates the value in real time as the user types.

Output:

react-controlled-components-example-1
  • Immediate Access to Input Data: The value is stored in state, making it easy to validate or modify.
  • Synchronous Updates: React can immediately respond to each change.
  • Predictable Behavior: Ensures a single source of truth as the state is the sole owner of the data.
  • More boilerplate code.
  • Can be less performant with a large number of fields due to constant re-renders.

An Uncontrolled Component manages its own state, with React simply “observing” it. Here, React doesn’t control the input field directly; instead, you access its value via the DOM using a ref.

Also Read: A Gentle Introduction to Refs in React (useRef Hook)

This approach lets the form elements maintain their own values, similar to how traditional HTML forms work.

UncontrolledInput.js

"use client"
import React, { useRef } from 'react'

const UncontrolledInput = () => {
	const inputRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Entered Value: ${inputRef.current.value}`);
  };
	return (
		<>
			 <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={inputRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
		</>
	)
}

export default UncontrolledInput

Output:

react-uncontrolled-components-example-1

In this example:

  • useRef creates a reference to the input element.
  • The inputRef.current.value accesses the current value only when needed (e.g., on form submission).
  • Less State Management: The form elements handle their state, reducing the need for state variables.
  • Simplicity in Small Forms: For simple forms, they require less code.
  • Improved Performance: Fewer re-renders compared to controlled components, especially with larger forms.
  • Limited control over each keystroke.
  • Delayed data access, as you must wait until submission or specific events to retrieve values.

Use Controlled Components When:

  • You need real-time validation.
  • Input values must be modified on the fly.
  • Form data is crucial for app behavior (like searching, filtering, or calculations).

Use Uncontrolled Components When:

  • You need simple forms or forms where values are only needed on submission.
  • Performance is a priority, especially in large forms.
  • You’re working with non-React libraries that manipulate DOM elements directly.

Both Controlled and Uncontrolled Components have their advantages and trade-offs. Controlled components offer more control and validation, while uncontrolled components can simplify state management and improve performance.

Choosing the right approach depends on the specific needs of your form and application complexity.

Key Takeaway: Start with controlled components for more complex forms or forms that require validation and consider uncontrolled components for simple, static forms where React doesn’t need to track every change.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.