less than 1 minute read

๐Ÿš€ useCallback()

useCallback์€ useMemo์™€ ๋น„์Šทํ•œ Hook์ž…๋‹ˆ๋‹ค. useMemo๋Š” ํŠน์ • ๊ฒฐ๊ด๊ฐ’์„ ์žฌ์‚ฌ์šฉํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ˜๋ฉด, useCallback์€ ํŠน์ • ํ•จ์ˆ˜๋ฅผ ์ƒˆ๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ์žฌ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

useCallback ์‚ฌ์šฉ๋ฒ•

const memoizedCallback = useCallback(function, deps);

useCallback์€ ์ฒซ ๋ฒˆ์งธ ์ธ์ž๋กœ ๋„˜์–ด์˜จ ํ•จ์ˆ˜๋ฅผ, ๋‘ ๋ฒˆ์งธ ์ธ์ž๋กœ ๋„˜์–ด์˜จ ๋ฐฐ์—ด ํ˜•ํƒœ์˜ ํ•จ์ˆ˜ ์‹คํ–‰ ์กฐ๊ฑด์˜ ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๊นŒ์ง€ ์ €์žฅํ•ด๋†“๊ณ  ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด ์ค๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด ๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ ์•ˆ์— ํ•จ์ˆ˜๊ฐ€ ์„ ์–ธ๋˜์–ด์žˆ์„ ๋•Œ ์ด ํ•จ์ˆ˜๋Š” ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง ๋  ๋•Œ๋งˆ๋‹ค ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๊ฐ€ ์ƒ์„ฑ๋˜๋Š”๋ฐ, useCallback์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง ๋˜๋”๋ผ๋„ ๊ทธ ํ•จ์ˆ˜๊ฐ€ ์˜์กดํ•˜๋Š” ๊ฐ’(deps)๋“ค์ด ๋ฐ”๋€Œ์ง€ ์•Š๋Š” ํ•œ ๊ธฐ์กด ํ•จ์ˆ˜๋ฅผ ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

const add = () => x + y;

์˜ˆ์‹œ๋กœ ์œ„์™€ ๊ฐ™์€ ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•  ๋•Œ useCallback์„ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ์ ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

const add = useCallback(() => x + y, [x, y]);

์ถœ์ฒ˜: https://cocoon1787.tistory.com/798

Tags:

Categories:

Updated:

Leave a comment