본문 바로가기
개발/React

[React] lodash를 활용한 debounce

by 그레이웅 2023. 3. 23. 00:21
반응형

lodash를 활용한 debounce

 

이전 포스팅에서 디바운스와 쓰로틀링에 대해 정리하였다.

 

Javascript를 사용할 때 아주 유용한 라이브러리 lodash란 라이브러리가 있다

 

이 라이브러리를 이용하면, debounce 이외에도 자바스크립트에서 지원하지 않는 편한 함수들을 지원해 준다.

 

공식 사이트는 아래와 같다.

 

https://lodash.com/

 

Lodash

_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn

lodash.com

 

다음과 같이 npm관리자 명령어로 설치가 가능하다.

//global
npm i -g npm

//
npm i --save lodash

 

 

lodash를 활용한 debounce 예시코드

import { useState, useCallback } from "react";
import debounce from "lodash/debounce";

const App = () => {
  const [text, setText] = useState("");

  const sendQuery = (query) => {
    // api 호출 
    console.log(query);
  };

  // 400ms 딜레이
  const delayedSearch = useCallback(
    debounce((q) => sendQuery(q), 400),
    []
  );

  const handleChange = (event) => {
    // input에 값이 변하면 바로 이 함수에 들어온다.
    setInputValue(event.target.value);
    
    // 타이핑이 끝날을때만 쿼리 호출
    delayedSearch(event.target.value);
  };

  return <input value={text} onChange={handleChange} />;
};

export default App;

 

 

실행 결과는 아래와 같다. 

 

api요청이나 쿼리를 날릴 때 handleChange가 실행될 때 모두 요청하는 것이 아닌, 

콘솔에 찍히는 것과 같이 텍스트 입력이 끝나는 마지막 동작이 일어난 후 400ms 후에 api요청이 실행되는 위치인 콘솔이 찍히게 된다.

 

이는 자동완성이나 버튼 클릭등의 api 호출이 다중으로 발생할 경우 마지막 이벤트를 감지하여 무분별한 api 호출을 방지할 수 있는 좋은 기능이다.

 

lodash를 사용하면 좀 더 편리하게 자바스크립트 함수를 구현할 수 있으며

도큐먼트에 좀 더 다양한 종류들이 있다.

 

편리한 기능들을 더 정리해 봐야겠다.

 

2023.03.19 - [개발/React] - [React] 디바운스(Debounce), 쓰로틀(Throttle)

 

[React] 디바운스(Debounce), 쓰로틀(Throttle)

디바운스(Debounce)와 쓰로틀(Throttle) - 디바운스와 쓰로틀 React상의 onChange 이벤트로 api의 요청을 계속해서 보낼 시, 서버의 과부하를 막기위해 사용한다. 쉽게 말하면 api 요청을 과도하게 할 경우

ijw9209.tistory.com

 

 

https://www.upbeatcode.com/react/how-to-use-lodash-in-react/

반응형

댓글