Debounce
Debounce๋ ๊ณผ๋ํ ์์ฒญ์ผ๋ก ๋ฐ์ํ ์ ์๋ ์ฑ๋ฅ ์ ํ ๋ฌธ์ ๋ฅผ ๊ฐ์ ํ ์ ์๋ ๋ฐฉ๋ฒ ์ค ํ๋๋ค.
input์ฐฝ์ ์ฐ์์ ์ผ๋ก ๊ฐ์ ์ ๋ ฅํ ๋, ์ด๋ฒคํธ ๋ณ๊ฒฝ์ด ๋ฐ์ํ๊ณ ๊ทธ๋๋ง๋ค ๋คํธ์ํฌ ์์ฒญ์ด ๋ฐ์ํ๊ฒ ๋๋๋ฐ, ์ด๋ฐ ๊ฒฝ์ฐ์ ์ง์์ ์ธ ์์ฒญ์ผ๋ก ์ธํด ๋คํธ์ํฌ ์ฉ๋๊ณผ ๋ฐฑ์๋ ๋ฑ ๊ณผ๋ถํ๊ฐ ๋ฐ์ํ ์ ์์ผ๋ฏ๋ก ์ฑ๋ฅ๋ฉด์์ ์ข์ง ๋ชปํ๋ค.
(์ ๋ฃ API์ ์ฌ์ฉํ ๊ฒฝ์ฐ์ ๋น์ฉ๋ฉด์ผ๋ก๋ ๋ฌธ์ ๊ฐ๋ฐ์ํ๋ค..๐ซ )
๐๐ป Debounce๋ฅผ ์ฌ์ฉํด, ์ฐ์์ ์ผ๋ก ๋ฐ์ํ๋ ์ด๋ฒคํธ ์ค ๋ง์ง๋ง ์ด๋ฒคํธ(๊ฒ์ํ ํค์๋) ๋ง์ ๊ธฐ์ ์ผ๋ก ๋คํธ์ํฌ ์์ฒญ์ ๋ณด๋ด, ์ฌ์ฉ์ ์ ๋ ฅ๊ณผ ๊ฐ์ ๋น๋ฒํ ์ด๋ฒคํธ๋ฅผ ์ฒ๋ฆฌํ ๋ ์ฌ์ฉํ๋ค.
useDebounce : ์ฌ์ฉ์ ์ ์ Hook
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])
return debouncedValue
}
๋๋ฐ์ด์ฑํ ๊ฐ๊ณผ ๋ฐ๋ฆฌ์ด ๋จ์์ ์ง์ฐ์ด๋ผ๋ ๋ ๊ฐ์ง ์ธ์๋ฅผ ์ฌ์ฉํด, ๋๋ฐ์ด์ฑ๋ ๊ฐ์ ๋ฐํํ๋ค.
ํํฌ๋ useEffect์ง์ ๋ ์ง์ฐ ํ์ ๋๋ฐ์ด์ค๋ ๊ฐ์ ์ ๋ฐ์ดํธํ๋ ์๊ฐ ์ ํ์ ์ค์ ํ๋ ๋ฐ ์ฌ์ฉ๋๋ค. ๋ํ ๊ฐ์ด๋ ๋ถํ์ค์ฑ์ด ๋ณ๊ฒฝ๋๋ฉด ์๊ฐ ์ด๊ณผ๋ฅผ ๋ช ํํ ํ๋ ์ ๋ฆฌ ๊ธฐ๋ฅ๋ ์์ฑํ๋ค.
throttling
์ฐ์ด์ด ๋ฐ์ํ ์ด๋ฒคํธ์ ๋ํด ์ผ์ ํ delay๋ฅผ ํฌํจ์์ผ ์ฐ์์ ์ผ๋ก ๋ฐ์ํ ์ด๋ฒคํธ๋ ๋ฌด์ํ๋ ๋ฐฉ์์ด๋ค. ์ฆ, delay์๊ฐ๋์ ํธ์ถ๋ ํจ์๋ฅผ ๋ฌด์ํด์ ์ผ์ ๊ฐ๊ฒฉ์ผ๋ก ์์ฒญ์ ์ฒ๋ฆฌํ๋ค.
scroll ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ ๋ ๋ณต์กํ ์์ ์ ํ๋๋ก ์ค์ ํ๋ค๋ฉด ์คํฌ๋กค์ ์ฌ๋ฆฌ๊ณ ๋ด๋ฆด๋๋ง๋ค ๊ต์ฅํ ์์ฃผ ์คํ๋๊ธฐ ๋๋ฌธ์, ๋ ์ด ๋ฐ์ํ ์ ์๋ค. ์ด๋ด๋ ์ฐ๋กํ๋ง์ ๊ฑธ์ด์ค๋ค!
๐๐ป ์ ํด์ง ์ผ์ ๊ฐ๊ฒฉ์ผ๋ก ์์ฒญ์ ์ฒ๋ฆฌํ๋ค. ์ผ์ ๊ฐ๊ฒฉ๋ง๋ค ์ ๊ธฐ์ ์ผ๋ก ์คํํด์ผํ๋ค๋ฉด throttle๋ก ์ฒ๋ฆฌํ๋ ๊ฒ์ด ์ ํฉํ๋ค.
https://hackernoon.com/how-to-use-debounce-in-nextjs