React 컴포넌트 리렌더링 최적화 - shouldComponentUpdate vs PureComponent
문제 상황
대시보드에서 실시간으로 데이터가 업데이트되는데, 변경되지 않은 차트 컴포넌트들까지 매번 리렌더링되는 문제가 있었다. Chrome DevTools Profiler로 확인하니 부모 컴포넌트의 state 변경 시 모든 자식이 렌더링되고 있었다.
해결 방법
1. shouldComponentUpdate 직접 구현
class ChartComponent extends React.Component {
shouldComponentUpdate(nextProps) {
return this.props.data !== nextProps.data;
}
render() {
return <div>{/* 차트 렌더링 */}</div>;
}
}
간단한 경우엔 이 방식이 명확했다. 하지만 props가 여러 개일 때 일일이 비교하는 코드가 장황해졌다.
2. PureComponent 활용
class ChartComponent extends React.PureComponent {
render() {
const { data, options } = this.props;
return <div>{/* 차트 렌더링 */}</div>;
}
}
PureComponent는 shallow comparison을 자동으로 해준다. props와 state를 얕은 비교하여 변경이 없으면 리렌더링을 스킵한다.
주의사항
PureComponent는 얕은 비교만 하기 때문에 nested object나 array를 props로 전달할 때 주의해야 한다. 불변성을 지키지 않으면 제대로 동작하지 않는다.
// 잘못된 예
this.setState({ items: this.state.items.push(newItem) });
// 올바른 예
this.setState({ items: [...this.state.items, newItem] });
결과
불필요한 리렌더링이 70% 이상 줄었고, 대시보드 반응 속도가 체감상 2배 이상 개선되었다. 앞으로는 컴포넌트 설계 단계에서부터 리렌더링 최적화를 고려해야겠다.