useMemo()์™€ useCallback() ์ •๋ฆฌํ•˜๊ธฐ

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



โœ”๏ธ ํŠน์ • ํ•จ์ˆ˜ ์žฌ์‚ฌ์šฉ useCallback()

  • ํ•œ๋ฒˆ ๋งŒ๋“  ํ•จ์ˆ˜๋ฅผ ํ•„์š”ํ•  ๋•Œ๋งŒ ์ƒˆ๋กœ ๋งŒ๋“ค๊ณ  ์žฌ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ
  • ์ปดํฌ๋„ŒํŠธ์—์„œ props๊ฐ€ ๋ฐ”๋€Œ์ง€ ์•Š์œผ๋ฉด Virtual DOM์— ์ƒˆ๋กœ ๋ Œ๋”๋งํ•˜๋Š” ๊ฒƒ ์กฐ์ฐจ ํ•˜์ง€ ์•Š๊ณ  ์ปดํฌ๋„ŒํŠธ์˜ ๊ฒฐ๊ณผ๋ฌผ์„ ์žฌ์‚ฌ์šฉ ํ•˜๋Š” ์ตœ์ ํ™” ์ž‘์—…์„ ํ• ๊ฑด๋ฐ, ์ด๋Ÿด ๊ฒฝ์šฐ ํ•จ์ˆ˜๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ํ•„์ˆ˜

  • ์ฃผ์˜ํ•  ์ ์€, ํ•จ์ˆ˜ ์•ˆ์—์„œ ์‚ฌ์šฉํ•˜๋Š” state ํ˜น์€ props ๊ฐ€ ์žˆ๋‹ค๋ฉด ๊ผญ, deps ๋ฐฐ์—ด์•ˆ์— ํฌํ•จ์‹œ์ผœ์•ผ ๋œ๋‹ค๋Š” ๊ฒƒ
    • ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด, ํ•จ์ˆ˜ ๋‚ด์—์„œ ํ•ด๋‹น ๊ฐ’๋“ค์„ ์ฐธ์กฐํ•  ๋•Œ ๊ฐ€์žฅ ์ตœ์‹ ์˜ ๊ฐ’์„ ์ฐธ์กฐํ•  ๊ฒƒ์ด๋ผ๊ณ  ๋ณด์žฅํ•  ์ˆ˜ ์—†๋‹ค;;
    • props๋กœ ๋ฐ›์•„์˜จ ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค๋ฉด, ์ด ํ•จ์ˆ˜๋„ deps` ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•ด์•ผ ํ•จ!


:: ์ฝ”๋“œ ์˜ˆ์‹œ

  • a์™€ b์˜ ๊ฐ’์ด ๋ณ€ํ•  ๋•Œ์—๋งŒ doSomething ํ•จ์ˆ˜๋ฅผ ์žฌ์‚ฌ์šฉํ•˜๊ธฐ
// ์ ์šฉํ›„
const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);




โœ”๏ธ ํŠน์ • ๊ฒฐ๊ณผ๊ฐ’ ์žฌ์‚ฌ์šฉ useMemo()

  • ์„ฑ๋Šฅ ์ตœ์ ํ™”๋ฅผ ์œ„ํ•˜์—ฌ ์—ฐ์‚ฐ๋œ ๊ฐ’์„ useMemo๋ผ๋Š” Hook์„ ์‚ฌ์šฉํ•˜์—ฌ ์žฌ์‚ฌ์šฉํ•  ๋•Œ ์‚ฌ์šฉ
  • useMemo๋Š” ์˜์กด์„ฑ์ด ๋ณ€๊ฒฝ๋˜์—ˆ์„ ๋•Œ์—๋งŒ ๋ฉ”๋ชจ์ด์ œ์ด์…˜๋œ ๊ฐ’๋งŒ ๋‹ค์‹œ ๊ณ„์‚ฐํ•œ๋‹ค
  • useMemo๋กœ ์ „๋‹ฌ๋œ ํ•จ์ˆ˜๋Š” ๋ Œ๋”๋ง ์ค‘์— ์‹คํ–‰!!!!
  • ์˜์กด์„ฑ ๋ฐฐ์—ด์ด ์—†์„ ๊ฒฝ์šฐ ๋ Œ๋”๋ง ํ•  ๋•Œ ๋งˆ๋‹ค ์ƒˆ๋กœ์šด ๊ฐ’์„ ๊ณ„์‚ฐํ•˜๋‹ˆ ์ฃผ์˜!

๋ฉ”๋ชจ์ด์ œ์ด์…˜(memorization): ์ด์ „์— ๊ณ„์‚ฐ ํ•œ ๊ฐ’์„ ์žฌ์‚ฌ์šฉํ•œ๋‹ค๋Š” ์˜๋ฏธ๋ฅผ ๊ฐ€์ง„๋‹ค


:: ์ฝ”๋“œ ์˜ˆ์‹œ

  • a์™€ b์˜ ๊ฐ’์ด ๋ณ€ํ•  ๋•Œ๋งŒ computeExpensiveValue ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ memoizedValue ๋‹ด๊ธฐ!
// ์ ์šฉํ›„
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);




โœ”๏ธ React.memo๋ฅผ ์‚ฌ์šฉํ•œ ์ปดํฌ๋„ŒํŠธ ๋ฆฌ๋ Œ๋”๋ง ๋ฐฉ์ง€

  • ์ปดํฌ๋„ŒํŠธ์˜ props ๊ฐ€ ๋ฐ”๋€Œ์ง€ ์•Š์•˜๋‹ค๋ฉด,
  • ๋ฆฌ๋ Œ๋”๋ง์„ ๋ฐฉ์ง€ํ•˜์—ฌ ์ปดํฌ๋„ŒํŠธ์˜ ๋ฆฌ๋ Œ๋”๋ง ์„ฑ๋Šฅ ์ตœ์ ํ™”๋ฅผ ํ•ด์ค„ ์ˆ˜ ์žˆ๋Š” React.memo ํ•จ์ˆ˜
  • ์ปดํฌ๋„ŒํŠธ์—์„œ ๋ฆฌ๋ Œ๋”๋ง์ด ํ•„์š”ํ•œ ์ƒํ™ฉ์—์„œ๋งŒ ๋ฆฌ๋ Œ๋”๋ง์„ ํ•˜๋„๋ก ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค


:: ์ฝ”๋“œ ์˜ˆ์‹œ

  • a์™€ b์˜ ๊ฐ’์ด ๋ณ€ํ•  ๋•Œ๋งŒ computeExpensiveValue ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•œ ๊ฒฐ๊ณผ๋ฅผ memoizedValue ๋‹ด๊ธฐ!
// ์ ์šฉํ›„
import React from 'react';

const User = (props) => {
  return (
   ///
  );
};

export default React.memo(User);