728x90
리액트는 내부 상태를 'Single Source of Truth' 로 관리하는 설계원칙을 가지고 있다.
이 의미는 모든 데이터 요소를 한 곳에서만 제어하도록 하는 것이다.
보통의 HTML 엘리먼트들은 내부적으로 어떤 데이터를 가지지 않아 문제가 없지만,
HTML 엘리먼트 자체적으로 데이터를 가지는 <form> 엘리먼트들인 <input>, <textarea>, <select> 들은 사용자가 DOM에서 직접 정보를 입력하면 해당 정보를 엘리먼트가 직접 보관하므로 SST에 위배된다.
Controlled Component (제어 컴포넌트)
제어 컴포넌트는 엘리먼트가 가지고 있는 컴포넌트가 직접 상태를 관리하는 컴포넌트 이다.
import React, { useState } from 'react';
const ControlledComponent = () => {
const [value, setValue] = useState('');
const change = (e) => {
setValue(e.target.value);
};
const click = () => {
console.log(value);
};
return (
<div>
<input value={value} onChange={change} />
<button onClick={click}>전송</button>
</div>
);
};
export default ControlledComponent;
UnControlled Component (비제어 컴포넌트)
비제어 컴포넌트는 상태를 직접 관리하지 않고, 엘리먼트의 참조만 컴포넌트가 소유하는 것이다.
import React, { useRef } from 'react';
const UnControlledComponent = () => {
const inputRef = useRef();
const click = () => {
console.log(inputRef.current.value);
};
return (
<div>
<input ref={inputRef} />
<button onClick={click}>전송</button>
</div>
);
};
export default UnControlledComponent;
728x90
'React' 카테고리의 다른 글
Redux Toolkit (0) | 2021.06.04 |
---|---|
useEffect (0) | 2021.02.02 |
useState의 이전 상태값 (0) | 2020.12.28 |
useState의 비동기적 동작 (0) | 2020.12.21 |
redux-promise (0) | 2020.12.18 |
댓글