In this article, we will learn about uncontrolled components
Unlike controlled components, uncontrolled components are where form elements are directly accessed and handled by the DOM itself. React does not handle the input's value and has no way of controlling/updating its value.
Before proceeding forward learn about useRef Hook clickhere
In order to access the element via the DOM, we use the useRef
Hook. Let's take a look at this example.
export default function App() {
const inputElement = useRef();
const onInputSubmit=(e)=>{
e.preventDefault();
alert(`The name you entered was: ${inputElement.current.value}`)
}
return (
<div className="App">
<form onSubmit={onInputSubmit}>
<label>
Enter your name:
<input
type="text"
ref={inputElement}
/>
</label>
<button type="submit">Enter</button>
</form>
</div>
)
The notable differences between the uncontrolled example and the controlled one should be obvious when we look at the code. There is no state management by React. We simply add a ref
attribute in the input element to get access to its value, inputElement.current.value
.
Controlled vs. Uncontrolled Components:
Controlled Components:
The value of the input element is managed by React.
The value is stored in React state.
The value can be manipulated using event handlers.
Suitable for complex forms that require data validation, error handling, and other advanced features.
Require more code to implement.
Uncontrolled Components:
The value of the input element is managed by the DOM.
The value can be accessed using the DOM API.
Suitable for simple forms that don't require complex data validation or manipulation.
Require less code to implement.
In summary, Uncontrolled components:
useRef
to access the form element directlyUse the
ref
attribute to get the form valueUseful for when you want to grab an individual DOM element quickly, or when there's an input deeply nested in a form, or it is an input where it doesn't have to be submitted, just a temporary value
Good to use for when you don't want to trigger a re-render, because for
useState
, if there are state changes, the component re-renders