์ฌ์ฉ ์คํ ๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ: React, lodash

Debounce ์ฌ์ฉ ๋ชฉ์ : ๊ฒ์์ input์ onChange๋ง๋ค ํจ์๊ฐ ํธ์ถ๋๋ ๊ฒ์ debounce๋ฅผ ํตํด ๋ฐฉ์ง
1. Input์ onChange๋ฅผ ํตํ api ํธ์ถ
์๋ ํจ์๋ฅผ ์ดํด๋ณด์.

์ด ํจ์๋ input์ ํ
์คํธ๋ฅผ ์
๋ ฅํ ๊ฒฝ์ฐ input์ onChange๋ฅผ ํตํด ํฌ์ผ๋ชฌ์ ์กฐํํ๋ api๋ฅผ ํธ์ถํ๋ค.
input์ onChange๋ input์ ๊ฐ์ด ์
๋ ฅ๋ ๋๋ง๋ค ํธ์ถ๋๊ธฐ ๋๋ฌธ์ ๊ธ์ ์ ๋งํผ handleSearch ํจ์๊ฐ ํธ์ถ๋๋ ๊ฒ์ ์๋์์ ๋ณผ ์ ์๋ค. (๊ฒ์ ์ฑ๋ฅ ์ ํ)

์ด๋ฅผ ๋ฐฉ์งํ๊ธฐ ์ํด lodash์ debounce ํจ์๋ฅผ ์ ์ฉํด ๋ณผ ๊ฒ์ด๋ค.
๐กLodash๋? A modern JavaScript utility library delivering modularity, performance & extras. (๊ณต์ ๋ฌธ์์์ ์ ์ํ๊ณ ์๋ lodash์ ์๋ฏธ์ด๋ค; ๋ชจ๋์ฑ, ์ฑ๋ฅ๊ณผ ์ถ๊ฐ ๊ธฐ๋ฅ ๋ฑ์ ์ ๊ณตํ๋ ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ ์ ํธ๋ฆฌํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ด๋ค.)
2. Lodash์ debounce ์ ์ฉ
$ npm i -g npm //npm ์ค์น ์๋ฃ์ ์๋ต
$ npm i --save lodash
์ ๋ช
๋ น์ด๋ฅผ ํตํด lodash๋ฅผ ์ค์นํ๋ค.
- Debounce๋?
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
import { debounce } from 'lodash';
ํ์ํ ํจ์ debounce๋ง ๊ตฌ์กฐ๋ถํด๋ก importํ๋ค. (์ ์ฒด lodash๋ฅผ importํ๋ ๊ฒ๋ณด๋ค ๋ฉ๋ชจ๋ฆฌ๊ฐ ํจ์ฌ ์ ๋ค)
const getPokemon = debounce(async (value: string) => {
await axios
.get(`https://pokeapi.co/api/v2/pokemon/${value}`)
.then((res) => {
setPokemon(res);
})
.catch((err) => {
return;
});
}, 300);
๊ทธ๋ฐ ๋ค์ ๊ธฐ์กด getPokemon ํจ์๋ฅผ debounce ํจ์๋ก ๊ฐ์ธ์ค๋ค ์ง์ฐ์๊ฐ์ ์ซ์๋ก ์ ์ด์ค๋ค. (์ ์์์์๋ 0.3์ด๋ก ์ค์ )
์ด๋ ๊ฒ ํ๋ฉด input์ ํ์ดํ์ด ๋๋๋ผ๋ ํจ์ ํธ์ถ์ 0.3์ด๋ง๋ค ํ๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
3. State ๋ณ๊ฒฝ๊ณผ debounce ๋์ ์ ์ฉ
๊ทธ๋ ๋ค๋ฉด ๋ง์ฝ state ๋ณ๊ฒฝ๊ณผ debouce๋ฅผ ํจ๊ป ํธ์ถํ ๊ฒฝ์ฐ debounce๋ ํจ๊ณผ์ ์ผ๋ก ์๋ํ ๊น?
์๋ handleSearch ํจ์๋ input์ onChange๊ฐ ํธ์ถ๋ ๋๋ง๋ค(๊ฐ์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค) ์คํ๋๋ค.
handleSearch๋ด์์ setText๋ฅผ ํตํด ๋ณํ๋ input๊ฐ์ ๋์์ ์ ์ฅํ๊ณ , debounce๋ฅผ ํตํด api๋ฅผ ํธ์ถํ๋ฉด ์๋์ ๊ฐ์ด ํจ์๊ฐ ๋ง๋ค์ด์ง๋ค.
const getPokemon = debounce(async (value: string) => {
await axios
.get(`https://pokeapi.co/api/v2/pokemon/${value}`)
.then((res) => {
setPokemon(res);
})
.catch((err) => {
return;
});
}, 300);
const handleSearch = (e) => {
setText(e.target.value);
getPokemon(e.target.value);
}
์ ํจ์์์ ๋ฌธ์ ์ ์ ์ฐ๋ฆฌ์ ์์๊ณผ ๋ค๋ฅด๊ฒ getPokemonํจ์๊ฐ 0.3์ด๋ง๋ค๊ฐ ์๋ input์ value๊ฐ ๋ฐ๋๋๋ง๋ค ํธ์ถ๋๋ค๋ ์ ์ด๋ค.
์ด ์ฝ๋์ ๋ฌธ์ ์ ์ setText ํจ์๋ฅผ ์คํํ ๋๋ง๋ค ์ปดํฌ๋ํธ๊ฐ ์ฌ๋ ๋๋ง๋์ด debounceํจ์๋ฅผ ํธ์ถํ๋ getPokemonํจ์๋ฅผ ์ฌ์์ฑํ๋ค๋ ์ ์ด๋ค.
4. ์ปดํฌ๋ํธ ์ฌ๋ ๋๋ง์ ๊ด๊ณ์์ด debounce ํจ์ ์คํํ๊ธฐ
const getPokemon = useCallback(debounce(async (value: string) => {
await axios
.get(`https://pokeapi.co/api/v2/pokemon/${value}`)
.then((res) => {
setPokemon(res);
})
.catch((err) => {
return;
});
}, 300),
[]
;
const handleSearch = (e) => {
setText(e.target.value);
getPokemon(e.target.value);
}
์ ๋ต์ useCallback ํจ์๋ก debounceํจ์๋ฅผ ๊ฐ์ธ์ฃผ๋ ๊ฒ์ด๋ค.
์์ getPokemon ํจ์๋ handleSearch์์ text๊ฐ ๋ณ๊ฒฝ์ด ๋์ด๋ ์ด ๋ณ์๋ฅผ ๊ตฌ๋
ํ์ง ์๊ธฐ ๋๋ฌธ์ debounceํจ์๋ฅผ ์ฌ์์ฑํ์ง ์๋๋ค.