PureComponent VS React.memo

dev.horang๐Ÿฏยท2024๋…„ 6์›” 18์ผ
1
post-thumbnail

๊ณต์‹๋ฌธ์„œ

๐Ÿ’ก PureComponent๋ž€?
ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ๋˜๋Š” Component๋กœ ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋กœ ๋„˜์–ด์˜ค๋Š” props ํ˜น์€ ๋‚ด๋ถ€์˜ state๋ฅผ ์ด์ „๊ฐ’๊ณผ ๋น„๊ตํ•˜์—ฌ ๋ณ€๊ฒฝ์‹œ ๋ฆฌ๋žœ๋”๋ง ๋˜๊ฒŒ ํ•ด์ฃผ๋Š” ์ปดํฌ๋„ŒํŠธ.

๐Ÿ’ก React.memo๋ž€?
๊ณ ์ฐจ์ปดํฌ๋„ŒํŠธ(HOC)๋กœ props ๊ฐ’์„ memoizingํ•˜๊ณ  ์žˆ๋‹ค๊ฐ€ ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜๋ฉด ํ•ด๋‹น HOC๋ฅผ ๋ฆฌ๋žœ๋”๋ง ๋˜๊ฒŒํ•ด์ฃผ๋Š” ํ•จ์ˆ˜.

์–ธ๋œป๋ณด๋ฉด ๋น„์Šทํ•ด ๋ณด์ด๋Š” PureComponent ์™€ React.memo๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฐจ์ด๊ฐ€ ์žˆ๋‹ค.

ํด๋ž˜์Šคํ˜• ์ปดํฌ๋„ŒํŠธ vs ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ

PureComponent๋Š” ํด๋ž˜์Šคํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ๋˜๋ฉฐ ์‚ฌ์šฉ ์‹œ ์‚ฌ์šฉํ•˜๋ ค๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ extend์‹œ์ผœ ์‚ฌ์šฉํ•œ๋‹ค.

import {PureComponent} from 'React'

Class ExampleComponent extends PureComponent {
...
}

React.memo๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ๋ฅผ ์œ„ํ•œ HOC๋กœ ์›ํ•˜๋Š” ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ์‹ธ์„œ ์‚ฌ์šฉํ•œ๋‹ค.

const ExampleComponent=memo(({ crying }: TCryingProps) => {
  return <p data-testid='dog'>๊ฐ•์•„์ง€ "{crying}"</p>;
});

props ๋น„๊ต, state ๋น„๊ต

PureComponent๋Š” props, state๋ฅผ ๋ชจ๋‘ ๋น„๊ตํ•˜์—ฌ ํ•˜๋‚˜๋ผ๋„ ๋ณ€๊ฒฝ๋˜๋ฉด ๋ฆฌ๋žœ๋”๋ง ๋œ๋‹ค. React.memo๋Š” props ๋งŒ ๋น„๊ตํ•˜์—ฌ ์ด์ „๊ณผ ๋‹ค๋ฅด๋ฉด ๋ฆฌ๋žœ๋”๋ง ๋œ๋‹ค.

PureComponent๋Š” React.memo๋ฅผ ์‚ฌ์šฉํ•ด์„œ class component์—์„œ ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ๋กœ ๋ณ€ํ™˜์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

๊ณต์‹๋ฌธ์„œ์˜ ์˜ˆ์‹œ๋ฅผ ์ฐธ์กฐํ•ด๋ณด์ž.

import { PureComponent, useState } from 'react';

class Greeting extends PureComponent {
  render() {
    console.log("Greeting was rendered at", new Date().toLocaleTimeString());
    return <h3>Hello{this.props.name && ', '}{this.props.name}!</h3>;
  }
}
const Greeting = memo(function Greeting({ name }) {
  console.log("Greeting was rendered at", new Date().toLocaleTimeString());
  return <h3>Hello{name && ', '}{name}!</h3>;
});

์œ„์˜ ์˜ˆ์‹œ์ฒ˜๋Ÿผ ํ•˜๋ฉด ๋ณ€ํ™˜์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

์‹ค์ œ ์‹ค๋ฌด๋‚˜ ์ฝ”๋“œ ์งค ๋•Œ ๊ธฐ์–ตํ•˜๊ณ  ์žˆ๋‹ค๊ฐ€ ๋ถˆํ•„์š”ํ•œ ๋ฆฌ๋žœ๋”๋ง์ด ์ผ์–ด๋‚ ๋•Œ ์ ์šฉํ•ด๋ด์•ผ๊ฒ ๋‹ค.!.

profile
์ข‹์•„ํ•˜๋Š”๊ฑธ ๋ฐฐ์šฐ๋Š”๊ฑด ์‹ ๋‚˜๐ŸŽต

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