React 16.3 라이프사이클 메서드 변경 대응
문제 상황
회사 프로젝트가 React 16.3으로 업그레이드하면서 콘솔에 경고 메시지가 쏟아졌다. componentWillReceiveProps와 componentWillMount를 사용하는 컴포넌트가 30개가 넘었다.
Warning: componentWillReceiveProps has been renamed, and is not recommended for use.
대응 방법
1. componentWillReceiveProps → getDerivedStateFromProps
기존 코드:
componentWillReceiveProps(nextProps) {
if (nextProps.userId !== this.props.userId) {
this.fetchUserData(nextProps.userId);
}
}
변경 후:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.userId !== prevState.prevUserId) {
return {
prevUserId: nextProps.userId,
shouldFetch: true
};
}
return null;
}
componentDidUpdate() {
if (this.state.shouldFetch) {
this.fetchUserData(this.props.userId);
this.setState({ shouldFetch: false });
}
}
2. componentWillMount → componentDidMount
API 호출은 어차피 componentDidMount에서 해야 맞다. SSR 환경에서도 문제가 없다.
결론
getDerivedStateFromProps는 static 메서드라 this에 접근할 수 없어 불편했다. 단순 props 비교는 괜찮지만, 복잡한 로직은 componentDidUpdate로 분리하는 게 나았다. 30개 컴포넌트 수정에 이틀 걸렸다.