코드도보통지

5관문. Component Inversion

관문 5 / 7

children prop 패턴으로 부모 리렌더가 자식에게 전파되지 않도록 컴포넌트 구조를 역전하라.

📖 이론 비급

Component Inversion: children의 렌더링 절연

<Parent><Child /></Parent>에서 Parent가 리렌더될 때 Child는 리렌더되지 않는다. Child의 엘리먼트는 Parent 밖에서 생성되었기 때문이다.

이 원리를 활용하면 React.memo 없이도 리렌더 전파를 물리적으로 차단할 수 있다. 비싼 컴포넌트를 children으로 전달받는 패턴은 우아한 성능 최적화 기법이다.

⚔️ 수련 코드

import { useState } from 'react';

// 문제: SlowComponent가 ColorBox와 함께 매번 리렌더된다
function SlowComponent() {
  // 무거운 렌더링 시뮬레이션
  const now = performance.now();
  while (performance.now() - now < 50) {}
  console.log('SlowComponent 렌더');
  return <p>느린 컴포넌트</p>;
}

// TODO: ColorBox가 children을 받도록 변경하고
// App에서 <ColorBox><SlowComponent /></ColorBox>로 사용하라
function ColorBox() {
  const [color, setColor] = useState('blue');
  return (
    <div style={{ background: color, padding: 16 }}>
      <button onClick={() => setColor(c => c === 'blue' ? 'red' : 'blue')}>색상 변경</button>
      <SlowComponent />
    </div>
  );
}

export default function App() {
  return <ColorBox />;
}