useMemo 로 성능 최적화

2022. 12. 14. 21:57프로그래밍/React

    목차

App.js

function App() {
  const [posts, setPosts] = useState([]);
  const [value, setValue] = useState('');

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((posts) => setPosts(posts));
  }, []);

  return (
    <div style={{ padding: '1rem' }}>
      <input type='text' onChange={(e) => setValue(e.target.value)} />
      <div style={{ display: 'flex' }}>
        <A message={value} posts={posts} />
        <B message={value} posts={posts} />
      </div>
    </div>
  );
}

 

A.js

모든 요소를 하나의 컴포넌트에 

export const A = ({ message, posts }) => {
  return (
    <div>
      <h1>A Component</h1>
      <p>{message}</p>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <p>{post.title}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

 

B.js

요소들을 여러 개의 컴포넌트로 나눔

const Message = ({ message }) => {
  return <p>{message}</p>;
};

const ListItem = ({ post }) => {
  return (
    <li>
      <p>{post.title}</p>
    </li>
  );
};

const List = ({ posts }) => {
  return (
    <ul>
      {posts.map((post) => (
        <ListItem key={post.id} post={post} />
      ))}
    </ul>
  );
};

export const B = ({ message, posts }) => {
  return (
    <div>
      <h1>B Component</h1>
      <Message message={message} />
      <List posts={posts} />
    </div>
  );
};

 

A 랑 B 컴포넌트 렌더링 속도 비교

 

A 컴포넌트가 더 느릴 줄 알았는데

B 컴포넌트가 더 느림..ㅠㅠ

 

성능 최적화를 해주어야 함

React.memo() 를 사용하면 됨

 

React.memo() 로 둘러쌓여 있는 경우 React 는 컴포넌트를 렌더링하고 결과를 기억함 (메모이징)

그 후 다음 렌더링이 일어날 때 렌더링하는 컴포넌트의 props 가 같으면 기억한 내용을 재사용함

 

B.js

const Message = React.memo(({ message }) => {
  return <p>{message}</p>;
});

const ListItem = React.memo(({ post }) => {
  return (
    <li>
      <p>{post.title}</p>
    </li>
  );
});

const List = React.memo(({ posts }) => {
  return (
    <ul>
      {posts.map((post) => (
        <ListItem key={post.id} post={post} />
      ))}
    </ul>
  );
});

 

결과 : B 컴포넌트 렌더링 속도가 훨씬 빨라짐