코드도보통지

6관문. State Colocation

관문 6 / 7

불필요하게 상위로 올라간 상태를 가장 가까운 컴포넌트로 내려서 렌더링 범위를 최소화하라.

📖 이론 비급

State Colocation: 상태는 필요한 곳 가장 가까이

상태를 루트에 두면 변경 시 전체 트리가 리렌더된다. "올리기(Lifting State)"만 알고 "내리기(Colocate)"를 모르면 성능 낭비가 쌓인다.

원칙: 상태는 그것을 사용하는 컴포넌트들의 가장 가까운 공통 조상에 두어라. 다른 컴포넌트가 필요 없다면 해당 컴포넌트 안에 가두어라. Context로 전역화하기 전에 먼저 Colocation을 고민하라.

⚔️ 수련 코드

import { useState } from 'react';

// 문제: count는 Counter 안에서만 쓰이는데 App에 있다
export default function App() {
  const [count, setCount] = useState(0);
  const [theme, setTheme] = useState('light');

  return (
    <div data-theme={theme}>
      <Header theme={theme} onToggle={() => setTheme(t => t === 'light' ? 'dark' : 'light')} />
      <Counter count={count} onIncrement={() => setCount(c => c + 1)} />
    </div>
  );
}

function Header({ theme, onToggle }) {
  return <button onClick={onToggle}>테마: {theme}</button>;
}

function Counter({ count, onIncrement }) {
  return (
    <div>
      <p>{count}</p>
      <button onClick={onIncrement}>+1</button>
    </div>
  );
}