Controlled and Uncontrolled Components | Shreya

Post

editor-img
Shreya
Oct 11, 2022

Controlled and Uncontrolled Components

https://reactjs.org/docs/uncontrolled-components.html

Despite the fact that React's team recommends using controlled components, this is a choice to be made by the developer considering the use case, context, and purpose of implementing the form.

So let's understand the types of components

...and when to use them

Controlled Components

As the name suggests these are the components whose value is controlled/driven/directed by React's state within the component.

The state within the component serves as “the single source of truth” for the input elements that are rendered by the component.

import { useState } from "react";export default function App() { const [inputValue, setInputValue] = useState(null); const handleOnChange = (event) => { setInputValue(event.target.value); } return ( <form> <h1>Controlled Component Example</h1> <label htmlFor="first-input">Start By Typing in below!</label> <br/> <input id="first-input" value={inputValue} onChange={handleOnChange}/> <br/> <br/> <span>State Variable's value:</span> <br/> <strong>{inputValue}</strong> </form> );}

In the above code snippet,

we have used a state inputValue, this is where the value that is entered into the textbox is stored.

Now, we have to change inputValue on every keystroke, which can be done using onChange.

We have created an onChange event handler handleOnChange which uses setInputValue() to update the state of the input.

Advantages of using controlled components:

  • The UI and the data are in sync
  • Form data can be passed between different components
  • The event handler and the value prop can be from the parent or a redux store
  • The React component acts as a source of truth for this component

Disadvantages of controlled components:

  • They render at each input change (you can verify this by adding a console.log to the component)
  • A controlled component can be a bad choice when large changes are required to be made to the component

Uncontrolled Components

These too as the name suggests, are the components whose value is not controlled by React's state. It is completely controlled by the DOM.

Instead of writing an event handler for the component, we use ref to retrieve the values from the DOM.

import { useRef } from "react";export default function App() { const inputValue = useRef(null); const handleOnClick = () => { console.log("#### inputValue",inputValue.current.value) } return ( <form> <h1>Controlled Component Example</h1> <label htmlFor="first-input">Start By Typing in below!</label> <br/> <input ref={inputValue} id="first-input"/> <br/> <br/> <button onClick={handleOnClick}>Submit</button> </form> );}

In the above code snippet,

we have created a ref inputValue and assigned it to the input. We don't need to have an event handler in an uncontrolled component.

Refs are often used as instance properties on a component.

Whenever you submit the form you can see the value on console.

Advantages of uncontrolled components:

  • No component re-renders
  • Browser DOM handles the changes to the element
  • Simple to use
  • Keeps track of the internal state

Disadvantages of uncontrolled components:

  • Cannot be used in complicated scenarios where we need to pass the value to different components
  • It’s not always efficient to use uncontrolled components where we require granular control over the value

Why are Controlled Components recommended over Uncontrolled Components?

The truth is, you’re supposed to use controlled components as much as possible. That is what the official documentation recommends and that is the easiest way for you to build reusable components.

In most cases, we recommend using 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.~ React's documentation

By working on the higher abstraction layer provided by React, you can worry about your actual business logic without even thinking about the internal workings of the DOM API.

This works for writing the actual application, and the associated unit tests and it even decreases the cognitive load required to mentally parse your code.

When to use Uncontrolled Components?

  • if you’re working on interacting with other libraries that don’t follow React’s design pattern then relying on a lower-level layer, like the DOM API will help you speak the same language, React, Vue, Angular, and any other framework, down at their code, they’re all speaking it you can use uncontrolled components.
  • Also, they are generally used when the use case is simple or the action is not trackable, for example, a user uploading a file using file input.