개인공부/etc

debounce, throttle 사용하는 이유 + SWR에서 debounce 훅 사용하기

minseokiim 2024. 8. 23. 19:32

 

* 문제

키워드 입력할 때마다 네트워크 요청이 가거나 상태가 변경되어 과부하가 발생할 수  있음.

 

* 해결방식

1. debouncing : 이벤트가 끝날 때 처리
키워드 입력/삭제할 때는 기다리다가 이벤트가 멈추면 네트워크 요청하게 할 수 있음

2. throttling : 일정 간격으로 끊어서 처리
이벤트가 지속적으로 일어나도 중간 중간에 지정한 간격 별로 끊어서 처리

 

디바운스는 lodash라이브러리를 많이 이용했는데, 이번 프로젝트를 구현하면서 훅으로 구현 하는 방식을 찾았다.

 

 

- 참고한 자료

https://github.com/vercel/swr/issues/110

 

Debounce? Throttle requests? · Issue #110 · vercel/swr

I'd like to debounce the request for the auto-suggestion example in this repository. So when a user types a search term, it waits 3000 ms before it fires a network request on the search term. I'm n...

github.com

 

 

1. // useDebounce.js

import { useState, useEffect } from 'react';

export default function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);



//1. delay 설정 시간 이전에 실행되어 변경되면 그 전의 timeout을 삭제해줌-> 제일 마지막 timeout이 실행됨

  return debouncedValue;
}

 

 

2. // myComponent

import useSWR from 'swr';

import { useDebounce } from '../../../utils/hooks';
...
  const [search, setSearch] = useState('');
  const debouncedSearch = useDebounce(search, 1000);
 
// 2. 값이 업데이트 되어 fetching까지 완료
 
const { data: res, isValidating } = useSWR(
    () =>
      debouncedSearch ? `/api/suggestion?value=${debouncedSearch}` : null,
    Api.fetcher,
  );

'개인공부 > etc' 카테고리의 다른 글

JWT(JSON Web Token) & Refresh Token  (0) 2024.08.26
.env의 종류와 우선순위  (0) 2024.08.26
Sanity 쿼리 언어 GROQ (Graph-Relational Object Queries)  (0) 2024.08.15
URL vs URI vs URN  (0) 2024.08.11
axios / fetch 차이  (0) 2024.07.10