๐Ÿ‘๏ธ useEffect์™€ useLayoutEffect์˜ ์ฐจ์ด์ 

Haizelยท2023๋…„ 5์›” 24์ผ
1
post-thumbnail

๊ธฐ์ˆ  ๋ฉด์ ‘์„ ๋Œ€๋น„ํ•ด ๊ฐœ๋…์„ ๐Ÿฐ ํ•œ์ž… ํฌ๊ธฐ๋กœ ์ž˜๋ผ ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
๊นƒํ—ˆ๋ธŒ๊ฐ€ ๊ถ๊ธˆํ•˜๋‹ค๋ฉด ๋†€๋Ÿฌ์˜ค์„ธ์š”!
๐Ÿ‘‰ ๊นƒํ—ˆ๋ธŒ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ (Since 2023.05.10 ~ )

๐Ÿ’ก ํ•„์ˆ˜ ์šฉ์–ด

  • Render : DOM Tree๋ฅผ ๊ตฌ์„ฑํ•˜๊ธฐ ์œ„ํ•ด ๊ฐ ์—˜๋ฆฌ๋จผํŠธ์˜ ์Šคํƒ€์ผ ์†์„ฑ์„ ๊ณ„์‚ฐํ•˜๋Š” ๊ณผ์ •
  • Paint : ์‹ค์ œ ์Šคํฌ๋ฆฐ์— Layout์„ ํ‘œ์‹œํ•˜๊ณ  ์—…๋ฐ์ดํŠธํ•˜๋Š” ๊ณผ์ •

useEffect


useEffect์€ ์ปดํฌ๋„ŒํŠธ๋“ค์ด render์™€ paint๋œ ํ›„์— ์‹คํ–‰๋˜๋ฉฐ, ๋น„๋™๊ธฐ์ ์ž…๋‹ˆ๋‹ค.

paint๋œ ํ›„์— ์‹คํ–‰๋˜๊ธฐ ๋•Œ๋ฌธ์—, useEffect ๋‚ด๋ถ€์— DOM์— ์˜ํ–ฅ์„ ์ฃผ๋Š” ์ฝ”๋“œ๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ํ™”๋ฉด ๊นœ๋นก์ž„ ํ˜„์ƒ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

useEffect์˜ Life cycle


useLayoutEffect


useLayoutEffect์€ ์ปดํฌ๋„ŒํŠธ๋“ค์ด render๋œ ํ›„์— ์‹คํ–‰๋˜๋ฉฐ, ๊ทธ ํ›„ paint๋ฉ๋‹ˆ๋‹ค. ์ฆ‰ ๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค.

paint๊ฐ€ ๋˜๊ธฐ ์ „์— ์‹คํ–‰๋˜๊ธฐ ๋•Œ๋ฌธ์— DOM์„ ์กฐ์ž‘ํ•˜๋Š” ์ฝ”๋“œ๊ฐ€ ์กด์žฌํ•˜๋”๋ผ๋„ ์‚ฌ์šฉ์ž๋Š” ๊นœ๋นก์ž„์„ ๊ฒฝํ—˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

useLayoutEffect์˜ Life cycle


์–ธ์ œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„๊นŒ?


useEffect

useLayoutEffect์€ ๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰๋˜์–ด ๋‚ด๋ถ€ ์ฝ”๋“œ๊ฐ€ ๋ชจ๋‘ ์‹คํ–‰๋œ ํ›„ painting ์ž‘์—…์„ ๊ฑฐ์นฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋กœ์ง์ด ๋ณต์žกํ•  ๊ฒฝ์šฐ ์‚ฌ์šฉ์ž๊ฐ€ ๋ ˆ์ด์•„์›ƒ์„ ๋ณด๋Š”๋ฐ๊นŒ์ง€ ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ฆฐ๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ์–ด ๋ณดํ†ต์˜ ๊ฒฝ์šฐ useEffect์˜ ์‚ฌ์šฉ์ด ๊ถŒ์žฅ๋ฉ๋‹ˆ๋‹ค. ๋Œ€ํ‘œ์ ์œผ๋กœ ๋ฐ์ดํ„ฐ fetch, event handler, state reset ์˜ ๊ฒฝ์šฐ useEffect์„ ๋งŽ์ด ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

useLayoutEffect

ํ™”๋ฉด์ด ๊นœ๋นก ๊ฑฐ๋ฆฌ๋Š” ์ƒํ™ฉ์ผ ๋•Œ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด ์•„๋ž˜์™€ ๊ฐ™์ด state๊ฐ€ ์žˆ๊ณ , ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ฒซ painting ์‹œ ๋‹ค๋ฅด๊ฒŒ ๋ Œ๋”๋ง ๋˜์–ด์•ผ ํ• ๋•Œ, useEffect์€ ์ฒ˜์Œ์— 0์ด ๋ณด์—ฌ์ง€๊ณ  re-rendering ๋˜๋ฉด์„œ ํ™”๋ฉด ๊นœ๋นก์ž„ ํ˜„์ƒ์ด ๋ฐœ์ƒํ•˜์ง€๋งŒ, useLayoutEffect์€ ์ฝ”๋“œ๊ฐ€ ๋ชจ๋‘ ์‹คํ–‰๋œ ํ›„ painting ๋˜๊ธฐ ๋•Œ๋ฌธ์— ํ™”๋ฉด ๊นœ๋นก์ž„ ํ˜„์ƒ์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

const Test = (): JSX.Element => {
  const [value, setValue] = useState(0);

  useLayoutEffect(() => {
    if (value === 0) {
      setValue(10 + Math.random() * 200);
    }
  }, [value]);

  console.log('render', value);

  return (
    <button onClick={() => setValue(0)}>
      value: {value}
    </button>
  );
};

๐Ÿ‘๏ธ codesandbox๋กœ ๋ณด๊ธฐ



๐Ÿ“Žย ์ฐธ๊ณ ๋ฌธ์„œ

profile
ํ•œ์ž… ํฌ๊ธฐ๋กœ ๋ฒ ์–ด๋จน๋Š” ๊ฐœ๋ฐœ์ง€์‹ ๐Ÿฐ

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