Home >Web Front-end >JS Tutorial >Controlled vs Uncontrolled Components in React
Controlled Components: React Components that control the state of form elements via state or props, i.e., every state mutation will have an associated handler function.
Characteristics
import React, { useState } from 'react'; function ControlledForm() { const [value, setValue] = useState(''); const handleChange = (event) => { setValue(event.target.value); }; return ( <form> <input type="text" value={value} onChange={handleChange} /> </form> ); }
Uncontrolled Components: React Component where DOM itself handles the form element's state. React accesses the input value via ref, which stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
Characteristics
import React, { useRef } from 'react'; function UncontrolledForm() { const inputRef = useRef(); const handleSubmit = (event) => { event.preventDefault(); alert('Input Value: ' + inputRef.current.value); }; return ( <form onSubmit={handleSubmit}> <input type="text" ref={inputRef} /> <button type="submit">Submit</button> </form> ); }
Here's a comparison table between controlled and uncontrolled components:
When to use when
Controlled - for real-time validations, input formatting, or immediate feedback.
Uncontrolled - used for simple use cases like file uploads pre-filled form value isn't frequent or needs to be deferred until form submission.
The above is the detailed content of Controlled vs Uncontrolled Components in React. For more information, please follow other related articles on the PHP Chinese website!