August 28, 2023
얼마 전 면접에서 질문을 받은 기억이 나서 리마인드 할 겸 정리한다. React에서 컴포넌트를 다룰 때, 이를 “Controlled” 및 “Uncontrolled”로 나누어 생각할 수 있다. 두 방식 간의 주요 차이점을 이해하는 것은 React와 상태 관리를 제대로 다루기 위해 중요하다.
Controlled Component는 React 상태(state)에 의해 제어되는 컴포넌트를 의미한다. 이러한 컴포넌트의 값(value)은 React의 state에 바인딩되어 있고, 변경될 때마다 콜백 함수(예: onChange)를 통해 상태를 업데이트한다.
import React, { useState } from 'react'
function ControlledComponent() {
const [inputValue, setInputValue] = useState('')
const handleChange = event => {
setInputValue(event.target.value)
}
return <input type="text" value={inputValue} onChange={handleChange} />
}
장점:
단점:
Uncontrolled Component는 DOM 자체에 값을 유지하는 컴포넌트를 의미한다. ref를 사용하여 DOM에서 직접 값을 가져올 수 있다.
import React, { useRef } from 'react'
function UncontrolledComponent() {
const inputRef = useRef(null)
const handleSubmit = () => {
console.log(inputRef.current.value)
}
return (
<>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
)
}
장점:
단점:
Controlled와 Uncontrolled Component는 각각의 장점이 있다. 프로젝트의 요구사항과 개발자의 선호도에 따라 적절한 방법을 선택해야 한다.