aotoyae

[React] Lodash : debouncing 라이브러리 본문

React

[React] Lodash : debouncing 라이브러리

aotoyae 2024. 2. 20. 21:12

 

 

💡 디바운싱을 쉽게 구현해 줄 라이브러리를 사용해보자.

 

npm i --save lodash or yarn add lodash

 

import { useState, useCallback } from "react";
import "./App.css";
import _ from "lodash";

function App() {
  const [searchText, setSearchText] = useState("");
  const [inputText, setInputText] = useState("");

  const handleSearchText = useCallback(
    _.debounce((text) => {
      setSearchText(text);
    }, 2000), // 2초뒤 실행
    []
  );

  const handleChange = (e) => { // input 이 바뀌면 실행
    setInputText(e.target.value); // inputText 실시간으로 보여줌
    handleSearchText(e.target.value); // searchText 디바운싱
  };

  return (
    <div>
      <h1>Lodash</h1>
      <input
        type="text"
        placeholder="입력값을 넣고 디바운싱 테스트를 해보세요."
        style={{ width: "300px" }}
        onChange={handleChange}
      />
      <p>Search Text : {searchText}</p>
      <p>Input Text : {inputText}</p>
    </div>
  );
}

export default App;

inpurt Text 엔 실시간으로 값이 담기고,

Search Text 엔 입력 완료 후 2초 뒤에 값이 담긴다.

 

👀 lodash 가 아니라 커스텀 디바운스를 만들어보자.

  const debounce = (callback, delay) => {
    let timerId = null;

    return (...args) => {
      if (timerId) clearTimeout(timerId);
      timerId = setTimeout(() => {
        callback(...args);
      }, [delay]);
    };
  };

  const handleSearchText = useCallback(
    debounce((text) => {
      setSearchText(text);
    }, 2000), // 2초뒤 실행
    []
  );

 

위와 같이 동작한다.