[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,105 +2,227 @@
|
||||
id: wiki-2026-0508-불필요한-리렌더링-방지
|
||||
title: 불필요한 리렌더링 방지
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-B13B4D]
|
||||
aliases: [Prevent Unnecessary Re-render, React 최적화, memoization, render optimization]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [frontend, react, performance, optimization, memoization]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - 불필요한 리렌더링 방지"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: react
|
||||
---
|
||||
|
||||
# [[불필요한 리렌더링 방지|불필요한 리렌더링 방지]]
|
||||
# 불필요한 리렌더링 방지
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> React 애플리케이션에서 성능 저하를 막기 위해 컴포넌트의 프롭스(Props), 상태([[State|State]]), 컨텍스트(Context) 변경으로 인한 연쇄적인 렌더링을 제어하고 최적화하는 기법입니다.
|
||||
## 매 한 줄
|
||||
> **"매 render 매 cheap by default — 매 measure first, 매 then memoize"**. React 매 default 의 parent render 의 child 의 모두 re-render — 매 보통 fast. 매 React Compiler (RC 2026) 의 auto-memoization 의 manual `useMemo`/`useCallback` 의 obsolescence 약속. 매 그 전 의 explicit memoization + state colocation.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
**1. 리렌더링의 원리 파악** React에서 컴포넌트는 자신의 상태나 프롭스가 변경되거나, 의존하고 있는 컨텍스트 값이 바뀌거나, 부모 컴포넌트가 리렌더링될 때 업데이트됩니다. 부모가 렌더링되면 자식 컴포넌트도 프롭스 변경 여부와 상관없이 렌더링되는 폭포수(Cascading) 현상이 발생합니다.
|
||||
## 매 핵심
|
||||
|
||||
**2. 메모이제이션(Memoization) 활용**
|
||||
### 매 re-render trigger
|
||||
- **State change** (`useState`, `useReducer`).
|
||||
- **Props change** (parent render).
|
||||
- **Context change** (consumer re-renders).
|
||||
- **Parent re-render** (default behavior).
|
||||
|
||||
- **`React.memo()`**: 컴포넌트의 프롭스를 얕은 비교(Shallow compare)하여 변경되지 않았으면 이전 렌더링 결과를 재사용합니다.
|
||||
- **`useMemo` 및 `useCallback`**: 무거운 계산 결과나 함수의 참조([[Reference|Reference]]) 안정성을 유지하여, 메모이제이션된 자식 컴포넌트에 새로운 참조가 전달되어 리렌더링이 발생하는 것을 막습니다.
|
||||
- 다만, 메모이제이션 자체에도 비용(오버헤드)이 발생하므로 성능 문제가 프로파일링된 경우에만 의도적으로 사용하는 것이 좋습니다.
|
||||
### 매 4가지 전략
|
||||
1. **State colocation** — state 의 use 의 곳 가까이 (lift down).
|
||||
2. **Memoization** — `React.memo`, `useMemo`, `useCallback`.
|
||||
3. **Context split** — separate frequently-changing from stable.
|
||||
4. **Component composition** — `children` prop 의 stable reference.
|
||||
|
||||
**3. [[React 19|React 19]] 컴파일러의 자동 최적화** React 19에 도입된 컴파일러는 빌드 타임에 코드를 분석하여 컴포넌트, 값, 콜백 함수에 자동으로 메모이제이션을 적용합니다. 이를 통해 수동으로 `useMemo`나 `useCallback`을 작성해야 했던 보일러플레이트를 줄여줍니다.
|
||||
### 매 응용
|
||||
1. List rendering (10k+ items → virtualization + memo).
|
||||
2. Form state (controlled inputs → debounced or uncontrolled).
|
||||
3. Global state (Zustand selector, Redux `useSelector` with shallowEqual).
|
||||
4. Heavy computation (`useMemo` for derived state).
|
||||
|
||||
**4. 상태 지역화(State Colocation)와 익명 함수 분리**
|
||||
## 💻 패턴
|
||||
|
||||
- 상태를 부모로 과도하게 끌어올리는(State Lifting) 것은 불필요한 컴포넌트 트리의 렌더링을 유발하므로, 상태는 최대한 사용하는 곳과 가까운 위치(Local)에 두어야 합니다. (예: 빈번하게 변하는 마우스 좌표 등)
|
||||
- JSX 내부에 익명 함수나 인라인 객체를 직접 선언하면 매 렌더링마다 새로운 참조가 생성되므로, 렌더링 성능에 악영향을 줍니다.
|
||||
### 1. React.memo for pure components
|
||||
```typescript
|
||||
import { memo } from 'react';
|
||||
|
||||
**5. [[Context API|Context API]] 최적화 및 상태 관리 라이브러리 사용** React 기본 Context는 내부 값이 하나라도 변경되면 이를 구독하는 모든 컴포넌트를 리렌더링시킵니다. 이를 방지하기 위해 컨텍스트를 업데이트 빈도별로 잘게 쪼개거나, Zustand, Jotai, Valtio와 같이 선택적 구독(Selective Subscription)과 미세 조정(Fine-grained) 업데이트를 지원하는 상태 관리 도구를 도입해야 합니다.
|
||||
interface ItemProps {
|
||||
id: string;
|
||||
name: string;
|
||||
onClick: (id: string) => void;
|
||||
}
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
export const Item = memo(function Item({ id, name, onClick }: ItemProps) {
|
||||
console.log('render:', id);
|
||||
return <li onClick={() => onClick(id)}>{name}</li>;
|
||||
});
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[React Performance Optimization|React Performance Optimization]], React 19 Compiler, 상태 관리 최적화 (Zustand, Jotai, Valtio), 재조정 ([[Reconciliation|Reconciliation]], Virtualization (리스트 가상화)
|
||||
- **Projects/Contexts:** 대규모 프론트엔드 아키텍처 설계, 고빈도 업데이트를 처리하는 실시간 대시보드
|
||||
- **Contradictions/Notes:** 많은 개발자들이 컴포넌트가 느려지면 습관적으로 조기 메모이제이션(Premature Memoization)을 적용하려 하지만, 비교 연산 자체의 오버헤드로 인해 컴포넌트가 작고 빠르다면 오히려 성능이 하락할 수 있습니다. 항상 React DevTools Profiler 등으로 측정(Measure)한 후 최적화를 적용해야 합니다.
|
||||
|
||||
---
|
||||
|
||||
_Last updated: 2026-04-14_
|
||||
|
||||
---
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
// custom comparator (rarely needed)
|
||||
export const ItemDeep = memo(Item, (prev, next) => prev.id === next.id && prev.name === next.name);
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. useCallback for stable function reference
|
||||
```typescript
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function List({ items }: { items: { id: string; name: string }[] }) {
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// without useCallback — new ref each render → all Item re-render
|
||||
const handleClick = useCallback((id: string) => setSelected(id), []);
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
return (
|
||||
<ul>
|
||||
{items.map(it => <Item key={it.id} {...it} onClick={handleClick} />)}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 3. useMemo for expensive computation
|
||||
```typescript
|
||||
import { useMemo } from 'react';
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
function Report({ rows }: { rows: Row[] }) {
|
||||
const stats = useMemo(() => {
|
||||
return {
|
||||
total: rows.reduce((a, r) => a + r.amount, 0),
|
||||
avg: rows.length ? rows.reduce((a, r) => a + r.amount, 0) / rows.length : 0,
|
||||
max: Math.max(...rows.map(r => r.amount)),
|
||||
};
|
||||
}, [rows]);
|
||||
|
||||
return <Summary {...stats} />;
|
||||
}
|
||||
```
|
||||
|
||||
### 4. State colocation (lift down)
|
||||
```typescript
|
||||
// BAD — input state at parent re-renders entire tree
|
||||
function App() {
|
||||
const [search, setSearch] = useState('');
|
||||
return (
|
||||
<>
|
||||
<input value={search} onChange={e => setSearch(e.target.value)} />
|
||||
<ExpensiveTree /> {/* re-renders on every keystroke */}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// GOOD — colocate input state in SearchInput
|
||||
function SearchInput({ onCommit }: { onCommit: (s: string) => void }) {
|
||||
const [v, setV] = useState('');
|
||||
return <input value={v} onChange={e => { setV(e.target.value); onCommit(e.target.value); }} />;
|
||||
}
|
||||
function App() {
|
||||
return <><SearchInput onCommit={...} /><ExpensiveTree /></>;
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Context split (avoid frequent re-renders)
|
||||
```typescript
|
||||
// BAD — single context, everything re-renders on theme change
|
||||
const AppCtx = createContext<{user: User; theme: 'light'|'dark'; cart: Item[]}>(...);
|
||||
|
||||
// GOOD — split by change frequency
|
||||
const UserCtx = createContext<User | null>(null); // rare change
|
||||
const ThemeCtx = createContext<'light'|'dark'>('light'); // user-toggled
|
||||
const CartCtx = createContext<Item[]>([]); // frequent
|
||||
|
||||
// only consumers of changed context re-render
|
||||
```
|
||||
|
||||
### 6. Children as stable prop (composition)
|
||||
```typescript
|
||||
// BAD — Wrapper re-renders => inner re-renders even if same JSX
|
||||
function App() {
|
||||
const [count, setCount] = useState(0);
|
||||
return <Wrapper>{<HeavyChild />}</Wrapper>; // HeavyChild created each render? No — JSX is reference
|
||||
}
|
||||
|
||||
// pattern: pass children to escape parent re-render
|
||||
function Wrapper({ children }: { children: ReactNode }) {
|
||||
const [internal, setInternal] = useState(0);
|
||||
return <div>{children}</div>; // children reference stable from parent
|
||||
}
|
||||
```
|
||||
|
||||
### 7. Zustand selector (subscribe slice)
|
||||
```typescript
|
||||
import { create } from 'zustand';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
const useStore = create<{ count: number; user: User; inc: () => void }>((set) => ({
|
||||
count: 0,
|
||||
user: { id: '1', name: 'A' },
|
||||
inc: () => set(s => ({ count: s.count + 1 })),
|
||||
}));
|
||||
|
||||
// only re-renders when count changes (not user)
|
||||
function Counter() {
|
||||
const count = useStore(s => s.count);
|
||||
return <span>{count}</span>;
|
||||
}
|
||||
|
||||
// shallow compare for object selector
|
||||
function Profile() {
|
||||
const { name, id } = useStore(useShallow(s => ({ name: s.user.name, id: s.user.id })));
|
||||
return <span>{id}: {name}</span>;
|
||||
}
|
||||
```
|
||||
|
||||
### 8. React Profiler (measure first)
|
||||
```typescript
|
||||
import { Profiler } from 'react';
|
||||
|
||||
function onRender(id: string, phase: 'mount' | 'update', actualDuration: number) {
|
||||
if (actualDuration > 16) console.warn(`${id} ${phase} took ${actualDuration}ms`);
|
||||
}
|
||||
|
||||
<Profiler id="List" onRender={onRender}>
|
||||
<List items={items} />
|
||||
</Profiler>
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 100s of items, fast props | `React.memo` + `useCallback`. |
|
||||
| 10k+ items | virtualization (react-window, TanStack Virtual). |
|
||||
| Heavy compute | `useMemo`. |
|
||||
| Frequent global state | Zustand selector / Redux Toolkit. |
|
||||
| Form input | uncontrolled (react-hook-form) or colocated state. |
|
||||
| React 19+ | RC compiler 의 auto-memo — manual 의 less needed. |
|
||||
|
||||
**기본값**: 매 measure first (React DevTools Profiler). 매 colocate state. 매 React Compiler (when stable) 의 auto-memo. 매 manual memo 의 hot paths only.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[React 성능 최적화]] · [[Memoization]]
|
||||
- 변형: [[React Compiler]] · [[Zustand]] · [[TanStack Query]]
|
||||
- 응용: [[가상 스크롤]] · [[Virtualization]] · [[Form Performance]]
|
||||
- Adjacent: [[React DevTools Profiler]] · [[State Colocation]] · [[Context API]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: measured perf bottleneck (Profiler), large list, heavy compute, frequent state updates.
|
||||
**언제 X**: 매 not measured — premature optimization. 매 fast already (< 16ms render).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Memoize everything**: `useMemo` 의 cost (deps compare) > savings 의 cheap compute.
|
||||
- **Inline object/array as prop**: `<Comp data={{a:1}} />` 매 new ref 매 every render — defeats memo.
|
||||
- **Context for everything**: monolithic context → all consumers re-render.
|
||||
- **`useCallback` w/o `React.memo` child**: useless — child still re-renders on parent.
|
||||
- **Premature optimization**: optimize before measuring.
|
||||
- **Mutating state directly**: `state.list.push(...)` — React doesn't detect change.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (React docs 2026, Kent C. Dodds patterns, React Compiler RFC).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with 8 patterns + React Compiler 2026 note |
|
||||
|
||||
Reference in New Issue
Block a user