재택근무 환경에서 React Context API 성능 개선

문제 상황

코로나로 인한 재택근무 전환 후, 팀원들이 VPN 환경에서 관리자 대시보드를 사용하면서 페이지가 느리다는 피드백이 들어왔다. React DevTools Profiler로 확인해보니 Context 값이 변경될 때마다 연관 없는 컴포넌트들까지 리렌더링되고 있었다.

기존에는 사용자 정보, 알림, 테마 설정 등을 하나의 Context에서 관리하고 있었다.

const AppContext = React.createContext();

function AppProvider({ children }) {
  const [user, setUser] = useState(null);
  const [notifications, setNotifications] = useState([]);
  const [theme, setTheme] = useState('light');

  const value = { user, setUser, notifications, setNotifications, theme, setTheme };
  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}

알림이 업데이트될 때마다 user나 theme를 사용하는 컴포넌트들도 함께 렌더링되는 구조였다.

해결 방법

Context를 도메인별로 분리하고, useMemo로 value 객체를 메모이제이션했다.

const UserContext = React.createContext();
const NotificationContext = React.createContext();
const ThemeContext = React.createContext();

function UserProvider({ children }) {
  const [user, setUser] = useState(null);
  const value = useMemo(() => ({ user, setUser }), [user]);
  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}

추가로 자주 변경되는 값(알림 카운트)은 별도 Context로 분리하고, React.memo로 컴포넌트를 감싸 불필요한 렌더링을 차단했다.

결과

Profiler 측정 결과 평균 렌더링 시간이 약 60% 감소했다. 특히 알림 폴링으로 3초마다 업데이트되던 부분에서 체감 성능이 크게 개선됐다.

Context API는 편리하지만 구조 설계 없이 사용하면 성능 문제가 생긴다는 점을 다시 확인했다.

재택근무 환경에서 React Context API 성능 개선