본문 바로가기
Coding/[Web] Frontend

[React] Controlled, Uncontrolled Component

by Gofo 2024. 10. 7.

Controlled, Uncontrolled Component

Controlled와 uncontrolled는 엄밀히는 기술 용어가 아니다. (사실상 디자인 패턴에 가깝다)

 

개념상 아래처럼 2개로 나누지만, 무조건 둘 중 하나로 구분되는 것이 아니라 하나의 컴포넌트에 두개의 개념이 혼재될 수 있다.

 

  • controlled component : 중요한 정보가  local state가 아닌 props에 의해 만들어지는 컴포넌트
  • uncontrolled component : local state를 이용하여 내부적인 정보를 관리하는 컴포넌트

 

예시

예를 들어, TextField라는 컴포넌트가 있을 때 이 컴포넌트를 이루는 중요한 정보는

  1. input 태그에 보여줄 정보인 <pre>value</pre>와
  2. 사용자가 input 이라는 행위를 이루었을 때 동작할 콜백 함수인 <pre>onChange</pre>

이다.

 

아래처럼 value와 onChange가 props를 통해 전달되는 경우를 controlled component라고 하고,

function TextField({value, onChange}) {
	return <input value={value} onChange={onChange} />
}

 

아래처럼 내부적인 state (local state)를 통해 관리되는 경우를 uncontrolled component라 한다.

function TextField() {
	const [value, setValue] = useState("");
	return <input value={value} onChange={(e) => setValue(e.target.value)} />
}

 

혼재 가능성

위의 예시처럼 관리되는 값이 적은 경우 controlled component나 uncontrolled component 중 하나로 명확히 구분될 수 있지만,

여러 개의 정보를 가진 컴포넌트는 일부의 정보는 controlled 되고, 일부의 정보는 uncontrolled 될 수 있다.

즉, 하나의 컴포넌트에 controlled와 uncontrolled의 개념이 혼재될 수 있다.

 

컴포넌트 작성 시 고려사항

리엑트 공식문서에서는 컴포넌트를 작성할 때

어떤 정보가 controlled 되어야하고, 어떤 정보가 controlled 될 필요 없는지 (uncontrolled) 고려해서

여러 컴포넌트에 정보가 공유되어야하는 경우 해당 정보를 부모 컴포넌트로 끌어올려서 정보가 controlled 될 수 있도록 하는 것이 좋다고 한다.

 


참고 

react document : controlled and uncontrolled component

https://react.dev/learn/sharing-state-between-components#controlled-and-uncontrolled-components

 

Sharing State Between Components – React

The library for web and native user interfaces

react.dev

 

 

 

댓글