Next.js
React에서 파생 상태를 계산 함수로 바꿔본 이유
useState에서 derived state를 따로 보관하면 동기화 문제가 생긴다. 렌더링할 때마다 계산하는 쪽이 더 안정적이다.
React에서 상태 관리를 하다 보면 하나의 상태로부터 다른 상태를 파생시키는 경우가 많다. 예를 들어 loading과 error를 분리해서 따로 관리하려고 할 수 있다.
문제: derived state를 따로 보관하는 방식
const [status, setStatus] = useState('idle');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
이렇게 하면 status가 바뀔 때마다 isLoading과 error를 수동으로 업데이트해야 한다. 누군가는 잊고 한 개만 업데이트하는 버그가 생긴다.
해결: 계산 함수로 바꿔보자
const [status, setStatus] = useState('idle');
const isLoading = status === 'loading';
const error = status === 'error' ? 'Something went wrong' : null;
이렇게 하면 status 하나만 관리하고, 나머지는 렌더링할 때마다 계산한다. 상태 불일치 버그가 완전히 사라진다.
TypeScript로는 union type이 더 깔끔하다
type Status = 'idle' | 'loading' | 'success' | 'error';
const status: Status = 'loading';
const isLoading = status === 'loading';
이렇게 하면 IDE에서 자동완성도 지원하고, 컴파일 타임에 타입 체크가 된다.