useCallback 으로 함수 최적화

2022. 12. 16. 19:39프로그래밍/React

    목차
const List = React.memo(({ posts, testFunc }) => {
  console.log('List compoents is rendering');
  return (
    <ul>
      {posts.map((post) => (
        <ListItem key={post.id} post={post} />
      ))}
    </ul>
  );
});

export const B = ({ message, posts }) => {
  const testFunc = () => {};
  console.log('B compoents is rendering');
  return (
    <div>
      <h1>B Component</h1>
      <Message message={message} />
      <List posts={posts} testFunc={testFunc} />
    </div>
  );
};

 

List 컴포넌트가 계속 렌더링됨

List 컴포넌트가 리렌더링 되는 것을 막으려면

useCallback() 을 사용하면 됨

export const B = ({ message, posts }) => {
  const testFunc = useCallback(() => {}, []);
  console.log('B compoents is rendering');
  return (
    <div>
      <h1>B Component</h1>
      <Message message={message} />
      <List posts={posts} testFunc={testFunc} />
    </div>
  );
};

 

useCallback() 을 사용하면

testFunc 함수가 새로 만들어지지 않기 때문에

List 컴포넌트가 리렌더링 되지 않음