Input에 글을 입력해봅시다

무제.mov

어떻게 해결할 수 있을까?

1️⃣ Throttling (쓰로틀링)

마지막 함수가 호출된 후 일정 시간 동안 함수가 호출되지 않게 하는 방법

화면 기록 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>

2️⃣ Debouncing (디바운싱)

계속해서 호출되는 함수 중 가장 마지막에 호출되는 함수만 호출되게 하는 것

화면 기록 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>
    </>
  );
}