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.
What Are Controlled Components?
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:
Benefits of Controlled Components:
- 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.
Drawbacks:
- More boilerplate code.
- Can be less performant with a large number of fields due to constant re-renders.
What Are Uncontrolled Components?
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:
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).
Benefits of Uncontrolled Components:
- 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.
Drawbacks:
- Limited control over each keystroke.
- Delayed data access, as you must wait until submission or specific events to retrieve values.
When to Use Each Approach
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.
Conclusion
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.
Add comment