Featured image of post React Controlled Components

React Controlled Components

Reactにおける制御コンポーネントと非制御コンポーネントの違いについて簡単にまとめる。

制御コンポーネント

Reactが値を制御するコンポーネント。

  • stateから値を呼び出して扱うため、リアルタイムな入力値の処理ができる
  • フォームに対してはvalueで値を当て込む
  • 入力の度に再レンダリングが発生する
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const ControlledComponent = () => {
  const [value, setValue] = useState<string>('');
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => setValue(e.target.value);
  const handleSubmitClick = () => console.log(value);

  return (
    <>
      <input type="text" value={value} onChange={handleInputChange} />
      <button onClick={handleSubmitClick}>Submit</button>
    </>
  );
};

非制御コンポーネント

Reactが値を制御しないコンポーネント(DOMが値を管理する)

  • 値は自前でDOMを参照する(PropsやuseRefする)ため、自由度が低い
  • フォームに対してはdefaultValueで初期値を当て込む
  • 再レンダリングが発生しない
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const UncontrolledComponent = (props: { value: string }) => {
  const ref = useRef<HTMLInputElement>(null);
  const handleSubmitClick = () => console.log(ref.current?.value);

  return (
    <div>
      <input type="text" defaultValue={props.value} ref={ref} />
      <button onClick={handleSubmitClick}>Submit</button>
    </div>
  );
};

参考