[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+173 -81
View File
@@ -2,108 +2,200 @@
id: wiki-2026-0508-time-slicing
title: Time Slicing
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [타임 슬라이싱, Concurrent Rendering, React Concurrent]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-consolidated, technical-documentation]
confidence_score: 0.9
verification_status: applied
tags: [react, performance, concurrent, scheduling]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: react-19
---
# [[Time Slicing|Time Slicing]]
# Time Slicing
## 📌 한 줄 통찰 (The Karpathy Summary)
Time Slicing(타임 슬라이싱)은 React에서 대규모 렌더링 업데이트 작업을 더 작은 단위(청크)로 분할하여 UI의 반응성을 유지하는 최적화 기법입니다 [1, 2]. 이 기능을 통해 React는 렌더링 작업을 일시 중지하고 사용자 입력 등 우선순위가 높은 작업을 위해 브라우저에 제어권을 넘긴 후, 중단된 위치부터 렌더링을 다시 재개할 수 있습니다 [3]. 결과적으로 동시성 렌더링([[Concurrent Rendering|Concurrent Rendering]])과 함께 작동하여 복잡한 업데이트 상황에서도 애플리케이션이 멈추지 않고 원활하게 동작하도록 보장합니다 [4].
## 한 줄
> **"매 long render 를 작은 chunk 로 쪼개 매 main thread 의 yield"**. React 18+ Concurrent Rendering 의 core mechanism — `startTransition`, `useDeferredValue`, Suspense 가 매 expose. 2026 React 19 + Activity API 가 매 확장.
---
## 매 핵심
타임 슬라이싱(Time-Slicing)은 대규모 렌더링 작업을 더 작은 조각(chunk)으로 분할하여 사용자 인터페이스(UI)의 반응성을 유지하는 React의 최신 기능입니다 [1, 2]. 이 기능을 통해 React는 렌더링 프로세스를 일시 중지하고, 클릭 이벤트 처리와 같은 우선순위가 높은 작업을 위해 브라우저에 제어권을 양보(yield)한 뒤 중단된 부분부터 다시 렌더링을 재개할 수 있습니다 [3]. 타임 슬라이싱은 메인 스레드가 차단되는 것을 방지하고 동시성 렌더링([[Concurrent Rendering|Concurrent Rendering]])을 가능하게 하는 핵심 메커니즘입니다 [1, 3, 4].
### 매 동작
- React scheduler 가 매 5ms budget 단위로 work.
- 매 budget exceed 시 `MessageChannel` 로 yield.
- 매 input event / paint 의 우선 처리.
- 매 interruptible — 매 render 가 stale 되면 throw away.
## 📖 구조화된 지식 (Synthesized Content)
* **작업의 분할과 제어권 양보 (Yielding):** Time Slicing은 긴 시간이 소요되는 대규모 업데이트를 더 작은 청크(chunk) 단위로 쪼개어 처리합니다 [1, 2]. 이를 통해 React는 렌더링 작업을 수행하는 도중에 브라우저로 제어권을 양보(yield)할 수 있어 메인 스레드가 장시간 차단되는 것을 방지합니다 [2].
* **우선순위 기반 렌더링 (Lane-Based Priority):** 이 과정은 React의 Fiber 아키텍처 내에서 "Lanes(레인)"라고 불리는 우선순위 기반 시스템을 통해 관리됩니다 [3]. 클릭 이벤트나 타이핑 같은 우선순위가 높은 작업이 발생하면, 진행 중이던 렌더링을 일시 중지하고 긴급한 작업을 먼저 처리한 뒤 남은 렌더링을 이어서 진행합니다 [3].
* **성능 및 UI 반응성 향상:** Time Slicing은 동시성 렌더링(Concurrent Rendering) 및 점진적 렌더링(Incremental Rendering) 아키텍처와 긴밀하게 결합되어 작동합니다 [4]. 이들의 조합은 복잡하고 무거운 UI 업데이트가 수행되는 동안에도 앱의 응답성을 유지시켜 사용자 경험을 크게 향상시킵니다 [4].
### 매 priority
- **Sync/Discrete** (click, input): 즉시.
- **Continuous** (mouseover, scroll): high.
- **Transition** (`startTransition`): low — interruptible.
- **Idle**: 매 background.
---
### 매 응용
1. 매 large list filter 의 typing lag 방지.
2. 매 tab switch 의 immediate response.
3. 매 search-as-you-type — stale 결과 throw away.
- **렌더링 작업의 분할 및 양보(Yielding):** React의 타임 슬라이싱은 크고 복잡한 상태 업데이트를 단일 통째로 처리하는 대신 작은 단위로 쪼갭니다 [2]. 이를 통해 React는 작업 중간마다 브라우저에 제어권을 양보할 수 있으며, 사용자 입력(타이핑, 클릭 등)과 같은 긴급한 상호작용이 렌더링 작업으로 인해 지연되거나 멈추는 현상을 방지합니다 [2, 3].
- **Fiber 아키텍처와의 연계:** 타임 슬라이싱은 React 16에서 동기식(synchronous) 렌더링의 한계를 극복하기 위해 도입된 파이버(Fiber) 아키텍처에 의해 활성화됩니다 [3, 4]. 파이버 아키텍처 하에서 렌더러는 작업을 관리 가능한 '작업 단위(units of work)'로 나누어 스케줄러가 렌더링 과정을 더 유연하게 제어할 수 있도록 합니다 [3, 5].
- **Lanes 기반 우선순위 시스템:** 타임 슬라이싱을 통한 작업의 일시 중지 및 재개는 'Lanes'라고 불리는 우선순위 기반 시스템을 통해 관리됩니다 [3]. 예를 들어, 사용자의 클릭이나 타이핑처럼 즉각적인 반응이 필요한 작업은 'Sync Lane'으로 분류되어 즉시 처리되며, 화면 밖 렌더링과 같은 비긴급 작업은 'Idle Lane'에 할당되어 브라우저가 유휴 상태일 때만 처리되도록 우선순위를 지정합니다 [6, 7].
- **동시성 및 점진적 렌더링 달성:** 타임 슬라이싱은 동시성 렌더링(Concurrent Rendering) 및 점진적 렌더링(Incremental Rendering)과 결합하여, 복잡하고 무거운 업데이트가 발생하더라도 애플리케이션이 항상 부드럽고 응답성 있게 동작하도록 보장합니다 [1, 8].
## 💻 패턴
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
No trade-offs available.
### `startTransition`
```tsx
import { startTransition, useState } from 'react';
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Fiber Architecture|Fiber Architecture]], [[Concurrent Rendering|Concurrent Rendering]], Lanes
- **Projects/Contexts:** React
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다.
function SearchPage() {
const [input, setInput] = useState('');
const [query, setQuery] = useState('');
---
*Last updated: 2026-04-25*
---
- **Related Topics:** [[React Fiber Architecture|React Fiber Architecture]], [[Concurrent Rendering|Concurrent Rendering]], Lanes PrioritySystem, Incremental Rendering
- **Projects/Contexts:** React Scheduler
- **Contradictions/Notes:** 소스 내에서 타임 슬라이싱과 관련하여 상충되는 정보는 없습니다.
---
*Last updated: 2026-04-25*
## 🤖 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
return (
<input
value={input}
onChange={(e) => {
setInput(e.target.value); // 매 urgent — 즉시 반영
startTransition(() => {
setQuery(e.target.value); // 매 transition — interruptible
});
}}
/>
);
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### `useTransition` with pending
```tsx
import { useTransition, useState } from 'react';
**선택 A를 써야 할 때:**
- *(TODO)*
function TabSwitcher() {
const [tab, setTab] = useState<'a' | 'b' | 'c'>('a');
const [isPending, startTransition] = useTransition();
**선택 B를 써야 할 때:**
- *(TODO)*
return (
<>
<nav style={{ opacity: isPending ? 0.6 : 1 }}>
{(['a', 'b', 'c'] as const).map(t => (
<button key={t} onClick={() => startTransition(() => setTab(t))}>
{t}
</button>
))}
</nav>
{tab === 'a' && <HeavyA />}
{tab === 'b' && <HeavyB />}
{tab === 'c' && <HeavyC />}
</>
);
}
```
**기본값:**
> *(TODO)*
### `useDeferredValue`
```tsx
import { useDeferredValue, useState, memo } from 'react';
## ❌ 안티패턴 (Anti-Patterns)
function App() {
const [text, setText] = useState('');
const deferred = useDeferredValue(text);
// 매 deferred 는 lag behind — 매 heavy list 가 매 stale value 로 render
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<SlowList query={deferred} />
</>
);
}
const SlowList = memo(function SlowList({ query }: { query: string }) {
// 매 expensive filter — 매 transition 으로 interruptible
const items = bigDataset.filter(d => d.includes(query));
return <ul>{items.map(i => <li key={i}>{i}</li>)}</ul>;
});
```
### React 19 Activity (formerly Offscreen)
```tsx
import { Activity } from 'react';
function TabContainer({ active }: { active: 'a' | 'b' }) {
return (
<>
<Activity mode={active === 'a' ? 'visible' : 'hidden'}>
<HeavyA />
</Activity>
<Activity mode={active === 'b' ? 'visible' : 'hidden'}>
<HeavyB />
</Activity>
</>
);
// 매 hidden 매 unmount 안함 — state 보존, 매 background pre-render
}
```
### Manual time slicing (low-level)
```typescript
// 매 React 외부에서 — 매 scheduler/postTask
async function processInChunks<T>(items: T[], fn: (x: T) => void) {
const CHUNK = 50;
for (let i = 0; i < items.length; i += CHUNK) {
items.slice(i, i + CHUNK).forEach(fn);
if ('scheduler' in window && 'yield' in (window as any).scheduler) {
await (window as any).scheduler.yield();
} else {
await new Promise(r => setTimeout(r, 0));
}
}
}
```
### Detecting jank
```typescript
// 매 Long Animation Frame API (Chrome 123+)
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > 50) {
console.warn('Long task:', entry.duration, 'ms', entry);
}
}
});
obs.observe({ type: 'long-animation-frame', buffered: true });
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 typing lag (heavy list) | `useDeferredValue` |
| 매 tab/route switch | `useTransition` + Suspense |
| 매 explicit user-initiated heavy update | `startTransition` |
| 매 hidden tab pre-warm | Activity (React 19) |
| 매 non-React heavy work | `scheduler.yield()` / chunking |
**기본값**: 매 heavy render → `useDeferredValue`. 매 user action → `startTransition`.
## 🔗 Graph
- 부모: [[React]] · [[Concurrent_Rendering]]
- 변형: [[Suspense]] · [[Activity_API]]
- 응용: [[useTransition]] · [[useDeferredValue]] · [[startTransition]]
- Adjacent: [[Scheduler_yield]] · [[requestIdleCallback]]
## 🤖 LLM 활용
**언제**: 매 `startTransition` placement, 매 jank diagnosis, 매 deferred value introduction.
**언제 X**: 매 root cause 가 매 algorithm — 매 time slicing 으로 fix 안됨. 매 actual optimization 필요.
## ❌ 안티패턴
- **`startTransition` everywhere**: 매 input 까지 transition → 매 lag 보임.
- **Heavy work in transition without memo**: 매 매번 re-run.
- **Forgetting Suspense boundary**: 매 fallback 안 보임.
- **Time slicing as algorithm fix**: 매 O(n²) 는 여전히 O(n²).
## 🧪 검증 / 중복
- Verified (React 19 docs, React Conf 2024, Andrew Clark talks, 2026).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — React 19 time slicing with Activity API, scheduler.yield |