코드도보통지

4관문. Zustand Interop

관문 4 / 7

Zustand selector로 컴포넌트가 필요한 상태만 구독하여 과다 리렌더를 방지하라.

📖 이론 비급

Zustand Interop: Context의 한계 극복

Context는 값이 바뀌면 모든 소비자를 리렌더한다. Zustand는 selector를 통한 선택적 구독을 지원하여 이 문제를 해결한다.

const count = useStore(state => state.count); count가 바뀔 때만 이 컴포넌트가 리렌더된다. 다른 상태 변경엔 반응하지 않는다. Context와 달리 Provider 없이 어디서든 직접 구독할 수 있다.

⚔️ 수련 코드

// npm install zustand 필요
import { create } from 'zustand';

// TODO: Zustand 스토어를 생성하라
// { count, theme, user }와 각각의 setter를 포함
const useStore = create((set) => ({
  count: 0,
  theme: 'light',
  user: null,
  // TODO: increment, toggleTheme, setUser 구현
}));

// TODO: 각 컴포넌트가 필요한 상태만 selector로 구독하게 하라
function Counter() {
  const count = useStore(state => state.count);
  const increment = useStore(state => state.increment);
  console.log('Counter 렌더');
  return <button onClick={increment}>카운트: {count}</button>;
}

function ThemeToggle() {
  const theme = useStore(state => state.theme);
  const toggleTheme = useStore(state => state.toggleTheme);
  console.log('ThemeToggle 렌더');
  return <button onClick={toggleTheme}>테마: {theme}</button>;
}

export default function App() {
  return <div><Counter /><ThemeToggle /></div>;
}