React question detail
What are uncontrolled components?
The Uncontrolled components are form elements (like <input>, <textarea>, or <select>) that manage their own state internally via the DOM, rather than through React state.
You can query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.
The uncontrolled components will be implemented using the below steps,
- Create a ref using
useRefreact hook in function component orReact.createRef()in class based component. - Attach this
refto the form element. - The form element value can be accessed directly through
refin event handlers orcomponentDidMountfor class components
In the below UserProfile component, the username input is accessed using ref.
import React, { useRef } from "react";
function UserProfile() {
const usernameRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
console.log("The submitted username is: " + usernameRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" ref={usernameRef} />
</label>
<button type="submit">Submit</button>
</form>
);
}
Note: Here, DOM is in charge of the value. React only accesses the value when needed (via ref).
Benefits:
- Less boilerplate — no need for
useStateandonChange. - Useful for quick form setups or when integrating with non-React code.
- Slightly better performance in very large forms (fewer re-renders).
In most cases, it's recommend to use controlled components to implement forms. In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
See Class
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleSubmit(event) {
alert("A name was submitted: " + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
{"Name:"}
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}