마지막 함수가 호출된 후 일정 시간 동안 함수가 호출되지 않게 하는 방법
화면 기록 2023-12-07 오전 4.39.47.mov
function App() {
const [textList, setTextList] = useState<string[]>([]);
const [throttle, setThrottle] = useState(false);
const throttling = (e) => {
if (throttle) return;
setThrottle(true);
setTimeout(() => {
setTextList([...textList, e.target.value]);
setThrottle(false);
}, 500);
};
return (
<>
<div className="App">
<div className="inputDiv">
<label htmlFor="testInput">아무 말이나 입력하세요!</label>
<input name="testInput" type="text" onChange={throttling} />
</div>
{textList.map((text, index) => (
<p key={index}>{text}</p>
))}
</div>
</>
);
}
<aside> 🤔
하지만 더 개선할 수 있는 방법은 없을까? 가령, 사용자가 키보드에서 더 이상 입력을 하지 않을 때라든지…
</aside>
계속해서 호출되는 함수 중 가장 마지막에 호출되는 함수만 호출되게 하는 것
화면 기록 2023-12-07 오전 4.48.32.mov
function App() {
const [textList, setTextList] = useState<string[]>([]);
const [text, setText] = useState("");
useEffect(() => {
const timer = setTimeout(() => {
setTextList([...textList, text]);
}, 500);
return () => clearTimeout(timer);
}, [text]);
return (
<>
<div className="App">
<div className="inputDiv">
<label htmlFor="testInput">아무 말이나 입력하세요!</label>
<input
name="testInput"
type="text"
onChange={(e) => setText(e.target.value)}
/>
</div>
{textList.map((text, index) => (
<p key={index}>{text}</p>
))}
</div>
</>
);
}