1. 이벤트 핸들러와 Effect 중 선택하기
2. 반응형 값 및 반응형 로직
3. Effect에서 비반응형 로직 추출하기
1-1. 이벤트 핸들러는 특정 상호 작용에 대한 응답으로 실행된다.
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
// ...
function handleSendClick() {
sendMessage(message);
}
// ...
return (
<>
<input value={message} onChange={e => setMessage(e.target.value)} />
<button onClick={handleSendClick}>Send</button>;
</>
);
}
sendMessage(message)
가 실행된다는 것을 확신할 수 있다.1-2. Effect는 동기화가 필요할 때마다 실행된다.
function ChatRoom({ roomId }) {
// ...
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [roomId]);
// ...
}
serverUrl
은 반응형 값
이 아니지만 roomId
와 message
는 반응형 값이다.const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
// ...
}
2-1. 이벤트 핸들러 내부의 로직은 반응형이 아니다.
// ...
sendMessage(message);
// ...
function handleSendClick() {
sendMessage(message);
}
sendMessage(message)
가 실행된다.2-2. Effect 내부의 로직은 반응형이다.
// ...
const connection = createConnection(serverUrl, roomId);
connection.connect();
// ...
roomId
가 변경되었다는 것은 다른 룸에 연결하고 싶다는 의미이다. useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect()
};
}, [roomId]);
createConnection(serverUrl, roomId)
및 connection.connect()
코드는 roomId
의 모든 고유값에 대해 실행된다.function ChatRoom({ roomId, theme }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
showNotification('Connected!', theme);
});
connection.connect();
// ...
function ChatRoom({ roomId, theme }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
showNotification('Connected!', theme);
});
connection.connect();
return () => {
connection.disconnect()
};
}, [roomId, theme]);
// ...
3-1. Effect Event 선언하기
3-2. Effect Event로 최신 props 및 state 읽기
3-3. Effect Event의 제한사항
3-*
내용들은 아직 안정된 버전의 React로 출시되지 않은 실험적인 API에 대해 설명하고 있어 참고만 하였음.https://developer.mozilla.org/ko/