Form elements should be either controlled or uncontrolled

  • REACT_MISUSED_CONTROLLED_COMPONENT
  • Error
  • Medium
  • react

This rule applies when a form element such as <input>, <textarea>, and <select> works as both controlled and uncontrolled element.

The followings are controlled elements whose values are controlled by React state and associated handler functions:

  1. A form element has value prop.
  2. <input> element of type radio or checkbox has checked prop.

In contrast, the followings are uncontrolled elements with the initial values:

  1. A form element has defaultValue prop.
  2. <input> element of type radio or checkbox has defaultChecked prop.

Therefore, a form element should not have both value and defaultValue props. Also, <input> element should not have both checked and defaultChecked props. React outputs a warning message if you set both props for a form element.

Noncompliant Code Example

View with compliant examples side by side
import { useState } from 'react';

export function MyInput() {
  const [value, setValue] = useState('');

  return (
    <input // REACT_MISUSED_CONTROLLED_COMPONENT alarm
      type="text"
      value={value}
      defaultValue="DeepScan"
      onChange={e => setValue(e.target.value)}
    />
  );
}

Compliant Code Example

View with noncompliant examples side by side
import { useState } from 'react';

export function MyInput() {
  const [value, setValue] = useState('DeepScan');

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

Version

This rule was introduced in DeepScan 1.8.0-beta.

See

Was this documentation helpful?