0% completed
An uncontrolled component is a form element where the DOM itself is responsible for managing its state. React does not control the value of the input directly. Instead, the DOM keeps track of it, and you can access the value only when needed.
In an uncontrolled component, you typically use the ref
attribute to interact with the DOM directly, allowing you to retrieve the input value at a later point (for example, when the form is submitted).
React.createRef()
or useRef()
in functional components.Example
Let's look at an example of an uncontrolled form element:
import React, { useRef } from 'react'; function UncontrolledForm() { const inputRef = useRef(null); // Create a ref to access the input const handleSubmit = (event) => { event.preventDefault(); alert(`Entered value: ${inputRef.current.value}`); // Access the input value using the ref }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" ref={inputRef} /> {/* No value or onChange */} </label> <button type="submit">Submit</button> </form> ); } export default UncontrolledForm;
In the example above:
input
field is uncontrolled because it doesn’t have a value
prop or onChange
handler.ref
is used to access the current value of the input field when the form is submitted.Uncontrolled elements offer several benefits, including:
Less Code: Uncontrolled components require fewer props and event handlers, resulting in reduced boilerplate code. The browser manages the input’s state internally, eliminating the need to manually synchronize state with the input value.
Better Performance: Since uncontrolled components do not rely on React state updates for every keystroke or change, the component avoids frequent re-renders. This can make uncontrolled components more performant, particularly for large forms or applications with many input fields.
Simpler Implementation: Uncontrolled components are easier to use for straightforward forms where you don’t need to track or manipulate the input data in real time. They are ideal for cases where you only need to retrieve form values on submission, rather than during every interaction.
There are a few drawbacks to using uncontrolled components namely:
In conclusion, uncontrolled components simplify form handling by reducing boilerplate code and improving performance for large forms. They are a great choice for simple use cases where real-time state tracking isn't required.
.....
.....
.....