Skip to content

Instantly share code, notes, and snippets.

@jonidelv
Created December 27, 2021 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonidelv/df068c2171a3711ca9023d079d9cea77 to your computer and use it in GitHub Desktop.
Save jonidelv/df068c2171a3711ca9023d079d9cea77 to your computer and use it in GitHub Desktop.
Controlled and Uncontrolled components

Controlled and Uncontrolled components

Two different ways to handle input components


When working on a React form you will need to handle difernet types of inputs, selects, textareas, etc. What is the best way to deal with state changes?

Controlled components

Takes the value through props and notifies changes through callbacks such as onChange. The data and the "source of truth" are kept in the component state.

const { useState } from 'react';

function Controlled () {
  const [value, setValue] = useState();

  return (
    <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
  )
}

Uncontrolled components

Stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

const { useRef } from 'react';

function Uncontrolled () {
  const inputRef = useRef();

  return (
    <input type="text" value={value} ref={inputRef} />
  )
}

Note

In most cases, React team recommends using controlled components to implement forms. In a controlled component, form data is handled by a React component through state which causes the component to be re-rendered every time a new value is changed. The alternative is to use uncontrolled components, where the form data is handled by the DOM itself, the component is not updated with each change, this can be more performant in some cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment