Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
BKJang opened this issue Oct 23, 2019 · 0 comments
Open

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

BKJang opened this issue Oct 23, 2019 · 0 comments
Labels
completed This is completed. Javascript This is related to Javascript. React This is related to React.

Comments

@BKJang
Copy link
Owner

BKJang commented Oct 23, 2019

❗️ 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

@BKJang BKJang added completed This is completed. Javascript This is related to Javascript. React This is related to React. labels Oct 24, 2019
@BKJang BKJang changed the title React.memo React.memo를 컴포넌트 리렌더링 최적화 Oct 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
completed This is completed. Javascript This is related to Javascript. React This is related to React.
Projects
None yet
Development

No branches or pull requests

1 participant