useEffect(() => {
setDisplayedText(''); // 새로운 응답이 오면 이전 텍스트를 초기화합니다.
let currentIdx = 0;
const typingInterval = setInterval(() => {
if (currentIdx < fullText?.length) {
setDisplayedText((prevText) => prevText + fullText[currentIdx]);
currentIdx++;
} else {
clearInterval(typingInterval); // 모든 글자를 표시했으면 인터벌을 중지합니다.
}
}, 50);
// 컴포넌트가 언마운트되거나 aiResponseData가 변경될 때 인터벌을 정리합니다.
return () => clearInterval(typingInterval);
}, [aiResponseData, fullText]); // aiResponseData가 변경될 때마다 이 효과를 다시 실행합니다.
[문제점]
상기의 코드의 currentIdx 변수를 setDisplayedText 내부에서 찍어보면 처음부터 0이 아니라 1인걸 확인할 수 있다. setState 콜백 함수로 실행되어 currentIdx++가 먼저 실행되기 때문이다. 따라서 fullText[currentIdx]는 0부터 시작하는 것이 아니라 1부터 저장이 된다.
useEffect(() => {
setDisplayedText(''); // 새로운 응답이 오면 이전 텍스트를 초기화합니다.
let currentIdx = 0;
const typingInterval = setInterval(() => {
const char = fullText[currentIdx];
if (currentIdx < fullText?.length) {
setDisplayedText((prevText) => prevText + char);
currentIdx++;
} else {
clearInterval(typingInterval); // 모든 글자를 표시했으면 인터벌을 중지합니다.
}
}, 50);
// 컴포넌트가 언마운트되거나 aiResponseData가 변경될 때 인터벌을 정리합니다.
return () => clearInterval(typingInterval);
}, [aiResponseData, fullText]); // aiResponseData가 변경될 때마다 이 효과를 다시 실행합니다.
[해결방안]
콜백 함수의 코드 블록과 분리하여 별도로 지역 변수로 만들어서 지정해주었다.
'React' 카테고리의 다른 글
| [React] Rendering은 어떻게 동작할까? (2/3) - Render 단계 (1) | 2024.02.15 |
|---|---|
| [React] Render의 진짜 의미와 동작 원리 (1/3) - Overview (0) | 2024.02.12 |
| [React] Component가 Instance, Element로 변화는 과정 (0) | 2024.02.08 |
| [React] useMemo를 사용한 화면 깜빡거림 제거 (0) | 2024.01.09 |
| [React] Typescript에서 React useRef 사용법 (0) | 2024.01.08 |