BKJang / dev-tips

📚 This repository is a collection of development tips and troubleshooting I have experienced during development.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React.memo를 컴포넌트 리렌더링 최적화

BKJang opened this issue · comments

❗️ How did I encounter this issue?

렌더링 최적화를 진행하던 중, React.memo를 사용하여 불필요한 렌더링을 줄이던 중, 기존 기능이 정상적으로 동작하지 않는 버그가 발생.

❓ What is the cause of this issue?

React.memo의 두번 째 인자로는 propsAreEqual 함수를 넘길 수 있는데 기존의 state값을 변경하던 함수에서 함수형 업데이트를 사용하지 않아 해당 함수가 최신 state값을 참조하지 못해서 발생.

🔨 What have I tried? How did you finally solve it?

export default React.memo(
  UserDetail,
  (prevProps, nextProps) => prevProps.userData === nextProps.userData
);

위와 같이 두번째 인자로 props를 비교할 수 있고 true를 반환하면 리렌더링을 하지 않는다.
단, 위의 로직이 제대로 동작하려면 해당 상태 값을 변경하는 함수에서 함수형 업데이트를 통해 변경해주어야 한다.

// Bad
setUserData({
  ...userData,
  [e.target.name]: [e.target.value]
})
// Good
setUserData(prevState => {
  const { name, value } = e.target;
  return {
    ...prevState,
    name: value
  }
})

🙏 Reference