-
제어 컴포넌트, 비제어 컴포넌트프론트엔드 개발자가 될거야./react 2023. 12. 5. 13:06
input같이 form 관련된 컴포넌트를 다룰 때 사용되는 개념
각각의 개념을 요약하자면,
제어 컴포넌트는 React로 폼 데이터를 관리하는 방식(useState)이고,
비제어 컴포넌트는 React의 상태를 사용하지 않고 폼 데이터를 관리하는 방식(useRef)이다.useState로 불필요한 렌더링이 필요없는 경우에는 useRef를 사용하는 것이 더 좋으니
각각의 상황에 따라 선택하여 사용해보자!
제어 컴포넌트 VS 비제어 컴포넌트
<제어 컴포넌트> (useState)
사용자 입력을 기반으로 자신의 state를 관리하고 업데이트한다.
즉, 사용자의 입력을 받는 컴포넌트에 event 객체를 이용해 setState()로 값을 저장하는 방식이다.
사용자가 입력한 값과 저장되는 값이 실시간으로 동기화된다.
제어 컴포넌트의 값은 항상 최신값을 유지한다. 새로운 입력 값이 생길때 마다 상태를 새롭게 갱신한다.
이는 데이터와 UI에서 입력한 값이 항상 동기화됨을 알 수 있다.const [input, setInput] = useState(""); const onChange = (e) => { setInput(e.target.value); }; return ( <div className="App"> <input onChange={onChange} /> </div> ); }
<비제어 컴포넌트> (useRef)
기존의 바닐라 자바스크립트와 크게 다르지 않은 방식이다.
우리는 바닐라 자바스크립트를 사용할 때 폼을 제출할때 (submit button)을 클릭할 때 요소 내부의 값을 얻어왔다.
비제어 컴포넌트 또한 이와 유사한 방식으로 사용된다.비제어 컴포넌트는 값이 실시간으로 동기화 되지 않는다.
필드에서 값을 트리거 해야 값을 얻을 수 있다. 사진에선 [전송] 버튼을 클릭하면 console에 값이 찍힌다.
[전송]버튼을 클릭해 트리거 하기 전까지의 값은 변경되지 않는다.export default function App() { const inputRef = useRef(); // ref 사용 const onClick = () => { console.log(inputRef.current.value); }; return ( <div className="App"> <input ref={inputRef} /> <button type="submit" onClick={onClick}> 전송 </button> </div> ); }
제어 컴포넌트 ⇒ 사용자가 입력을 하는 액션을 취할때마다 리렌더링을 발생시킴
비제어 컴포넌트 ⇒ 사용자가 직접 트리거 하기 전까지는 리렌더링을 발생시키지도 않고 값을 동기화 시키지도 않음(클릭을 해야함)1. 즉각적으로 값에 대한 피드백이 필요하다. => 제어 컴포넌트 사용 (useState)
ex) 즉각적인 유효성 검사, 버튼 disable처리, input에 숫자만 입력가능한 상황
2. 즉각적인 피드백이 불필요하고 최종적인 값만 필요하다. 불필요한 렌더링 필요없다. => 비제어 컴포넌트 사용 (useRef)
ex) [전송]버튼 클릭 후, 값 체크
- 참고
'프론트엔드 개발자가 될거야. > react' 카테고리의 다른 글
[리액트 공식문서 정독하기] 리액트 주요개념 - 3 (폼, 합성 vs 상속, React로 생각하기) (0) 2023.08.19 [리액트 공식문서 정독하기] 리액트 주요개념 - 2 (이벤트 처리하기, React에서 콜백 함수 사용 시 주의할 점) (1) 2023.08.09 Fontsource로 폰트 적용하기 (0) 2023.08.08 [리액트 공식문서 정독하기] 리액트 주요개념 - 1 (JSX, DOM에 React 엘리먼트를 렌더링하는 방법, Components와 Props) (0) 2023.08.08 페이지의 특정 부분으로 스크롤하는 방법 (0) 2023.08.07