๐Ÿ”Ž ํฌ์ŠคํŠธ ๊ฒ€์ƒ‰๊ณผ ๋””๋ฐ”์šด์Šค

๋ฐ•์ƒ์€ยท2022๋…„ 5์›” 11์ผ
0

โœ๏ธ blelog โœ๏ธ

๋ชฉ๋ก ๋ณด๊ธฐ
12/13

ํฌ์ŠคํŠธ ๊ฒ€์ƒ‰ ๋กœ์ง์— debounce์ ์šฉ์— ๋Œ€ํ•œ ํฌ์ŠคํŠธ์ž…๋‹ˆ๋‹ค.

๐Ÿ“ข ์ฃผ์˜ ์‚ฌํ•ญ

์•„์ง ๋ฐฑ์—”๋“œ์™€ ์—ฐ๊ฒฐํ•˜์ง€ ์•Š๊ณ  ํ”„๋ก ํŠธ์ธก ์ฝ”๋“œ๋งŒ ์ž‘์„ฑํ•˜๊ณ  ๊ฐ€์งœ ๋ฐ์ดํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ ํ™”๋ฉด์— ๋ Œ๋”๋งํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋น„์Šทํ•œ ํ˜•ํƒœ์˜ ํฌ์ŠคํŠธ๋งŒ ๋ Œ๋”๋ง๋˜๊ณ  ๋งŽ์€ ํฌ์ŠคํŠธ๊ฐ€ ์กด์žฌํ•˜์ง€๋Š” ์•Š์Šต๋‹ˆ๋‹ค.

๐Ÿค” debounce

debounce๋ž€ ์ผ์ •์‹œ๊ฐ„๋‚ด์— ์—ฌ๋Ÿฌ๋ฒˆ ๋™์ผํ•œ ์š”์ฒญ์ด ์˜จ๋‹ค๋ฉด, ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ์š”์ฒญ๋งŒ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

ํฌ์ŠคํŠธ ๊ฒ€์ƒ‰ ์‹œ input์— ํ•˜๋‚˜์˜ ๊ธ€์ž๋ฅผ ์ž…๋ ฅํ•  ๋•Œ๋งˆ๋‹ค ํฌ์ŠคํŠธ๋“ค์„ ์š”์ฒญํ•˜๋Š” ๊ฒƒ๋ณด๋‹จ ์ ์ ˆํ•œ ๋‹จ์–ด๊ฐ€ ์ž…๋ ฅ๋˜์—ˆ์„ ๋•Œ ํฌ์ŠคํŠธ๋“ค์„ ์š”์ฒญํ•˜๋Š” ๊ฒƒ์ด ํ›จ์”ฌ ํšจ์œจ์ ์ธ ๋™์ž‘ ๋ฐฉ์‹์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ์ž…๋ ฅ ํ›„ 0.3์ดˆ๊ฐ€ ์ง€๋‚˜๋ฉด ํ˜„์žฌ ์ž…๋ ฅ๋œ ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ•ด์„œ ๊ฒŒ์‹œ๊ธ€ ๊ฒ€์ƒ‰์— ๋Œ€ํ•œ ์š”์ฒญ์„ ๋‚ ๋ฆฌ๋„๋ก ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

๐Ÿ˜Ž ์ ์šฉ ์˜ˆ์‹œ

  • debounce ๋ฏธ์ ์šฉ
    no-debounce

  • debounce ์ ์šฉ
    debounce

โœ๏ธ ์ž‘์„ฑ ์ฝ”๋“œ

ํฌ์ŠคํŠธ๋“ค์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๋กœ์ง๋ถ€ํ„ฐ ์ „๋ถ€ ์ž‘์„ฑํ•˜๊ธฐ์—๋Š” ์ฝ”๋“œ๋Ÿ‰์ด ๋„ˆ๋ฌด ๋งŽ์•„์„œ ๋””๋ฐ”์šด์‹ฑ์„ ์ ์šฉํ•˜๋Š” ๋ถ€๋ถ„๋งŒ ์ž‘์„ฑํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
์ถ”ํ›„์— ๊นƒํ—™์— ์—…๋กœ๋“œ ์‹œ ์ „์ฒด ์ฝ”๋“œ ๋งํฌ ์ถ”๊ฐ€ํ•˜๊ธฐ

// 2022/05/11 - ๋””๋ฐ”์šด์‹ฑ์— ์‚ฌ์šฉํ•  ํƒ€์ด๋จธ ์•„์ด๋”” ์ €์žฅ ๋ณ€์ˆ˜ - by 1-blue
const timerId = useRef<ReturnType<typeof setTimeout> | null>(null);
// 2022/05/11 - ๋””๋ฐ”์šด์‹ฑ ๋ณ€์ˆ˜ - by 1-blue
const [debounce, setDebounce] = useState(true);
// 2022/05/11 - ํ˜„์žฌ ํ‚ค์›Œ๋“œ ๊ฐ’ ์ €์žฅํ•  ๋ณ€์ˆ˜ - by 1-blue
const [currentKeyword, setCurrentKeyword] = useState("");
// 2022/05/11 - ํ‚ค์›Œ๋“œ ๋ณ€๊ฒฝ ์ด๋ฒคํŠธ ํ•จ์ˆ˜ - by 1-blue
const onChangeKeyword = useCallback(
  (e: React.ChangeEvent<HTMLInputElement>) => {
    setCurrentKeyword(e.target.value);
    setDebounce(false);

    if (timerId.current) clearTimeout(timerId.current);
    timerId.current = setTimeout(() => setDebounce(true), 300);
  },
  [timerId]
);

// ์ดํ›„์— debounce๋ฅผ ์ด์šฉํ•ด์„œ ๊ฒ€์ƒ‰ ์š”์ฒญ ๋ณด๋‚ด๊ธฐ

0๊ฐœ์˜ ๋Œ“๊ธ€