Understanding when to use controlled versus uncontrolled components is essential for building React forms. Here's a comprehensive guide to both approaches.
Controlled Components#
Uncontrolled Components#
Controlled Form Example#
Uncontrolled Form Example#
File Inputs (Always Uncontrolled)#
Hybrid Approach#
Controlled Select#
Controlled Checkbox#
Controlled Radio Buttons#
Formatting Input Values#
Reset Form#
Comparison Table#
Feature | Controlled | Uncontrolled
-------------------------|-------------------|------------------
Value source | React state | DOM
Re-renders on input | Yes | No
Real-time validation | Easy | Manual
Form submission | From state | From refs
Initial value | value prop | defaultValue prop
File inputs | Not supported | Supported
Performance | More re-renders | Fewer re-renders
Testing | Easier | Requires DOM
Best Practices#
Use Controlled When:
✓ Real-time validation needed
✓ Conditional field disabling
✓ Input formatting required
✓ Dynamic form modifications
✓ Multiple inputs depend on each other
Use Uncontrolled When:
✓ Simple forms with minimal validation
✓ File inputs
✓ Performance is critical
✓ Integrating with non-React code
✓ One-time value reading
General Tips:
✓ Stay consistent within a form
✓ Use controlled for complex interactions
✓ Consider form libraries for large forms
✓ defaultValue, not value, for uncontrolled
Conclusion#
Controlled components give you full control over form state through React, enabling real-time validation, formatting, and dynamic behavior. Uncontrolled components let the DOM handle state, offering better performance for simple forms. Choose controlled for interactive forms needing validation, and uncontrolled for simple forms or file inputs. For complex forms, consider using form libraries like React Hook Form that offer the best of both approaches.