Open In App

When to use an uncontrolled component in React?

Uncontrolled Components are the components that are not controlled by the React state or any functions and are handled by the DOM (Document Object Model). So to access any value that has been entered we take the help of refs. In an uncontrolled component, the component manages its state internally. Common use cases for uncontrolled components include simple input fields or elements that don’t need control.

Approach to use Uncontrolled Components in React:

Example 1: In this example we are creating a simple form that contains an input field with a label and a submit button with an onSubmit function that triggers when we submit the form. We are accessing the text we have filled in the input section using useRef.






import React, { useRef } from 'react'
 
function App() {
    const inputRef = useRef()
 
    const handleSubmit = (event) => {
        event.preventDefault()
        alert(
            `Submitted value:
            ${inputRef.current.value}
            `)
    }
 
    return (
        <form onSubmit={handleSubmit}>
            <label>
                Enter something:
            </label>
            <input type="text" ref={inputRef} />
            <button type="submit">Submit</button>
        </form>
    )
}
 
export default App

Output:

Example 2: In this example there is an input field to take file as an input and a button that triggers a function on click. We are accessing the name of the file we have filled in the input section using useRef.






function App() {
    const fileInputRef = useRef();
 
    const handleFileUpload = () => {
        const selectedFile =
            fileInputRef.current.files[0];
        alert(
            `Submitted value: ${selectedFile.name}`
        )
    };
 
    return (
        <div>
            <input type="file"
                ref={fileInputRef} />
            <button onClick={handleFileUpload}>
                Upload
            </button>
        </div>
    );
}
 
export default App

Output:

Advantages of using Uncontrolled Components:

Disadvantages of Uncontrolled Components:


Article Tags :