Files
2nd/10_Wiki/Topic_Programming/Frontend/Automatic Batching.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

4.6 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-automatic-batching Automatic Batching (React 18+) 10_Wiki/Topics verified self
React Batching
Concurrent Batching
none A 0.9 applied
react
batching
performance
rendering
2026-05-10 pending
language framework
TypeScript React 19

Automatic Batching (React 18+)

매 한 줄

"매 setState 매 합쳐서 매 한 번 render". React 18에서 도입된 automatic batching은 모든 update (promise, setTimeout, native event)를 single re-render로 group한다. React 17 이전엔 React event handler 안에서만 batching이었음 — 이제 전부 자동.

매 핵심

매 동작

  • 매 동일 tick 안의 setState calls → React가 모아서 하나의 commit 으로 처리.
  • 결과: less render, less DOM mutation, less component lifecycle invocation.
  • React 19도 동일 model 유지 + Compiler 가 추가 optimization.

React 17 vs 18+

  • 17: onClick 안 batching O / setTimeout, Promise.then 안 batching X.
  • 18+: 매 모든 context batching O.
  • Opt-out: flushSync() 로 immediate render 강제.

매 응용

  1. Form state with multiple fields — 매 single render.
  2. Async fetch chain — 매 single render after Promise.
  3. Concurrent transitions — startTransition + batching.

💻 패턴

React 18 default behavior

import { useState } from 'react';

function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [age, setAge] = useState(0);

  async function handleSubmit() {
    const res = await fetch('/api/me');
    const data = await res.json();
    // 18+: 매 3 setState 매 single render
    setName(data.name);
    setEmail(data.email);
    setAge(data.age);
  }

  return <button onClick={handleSubmit}>Load</button>;
}

flushSync to opt out

import { flushSync } from 'react-dom';

function handleClick() {
  flushSync(() => {
    setCount(c => c + 1);
  });
  // 매 DOM 업데이트 매 done — measure 가능
  const h = listRef.current.scrollHeight;
  flushSync(() => {
    setHeight(h);
  });
}

Custom hook with batched async

function useAsyncForm<T>() {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  async function load(fn: () => Promise<T>) {
    setLoading(true);
    setError(null);
    try {
      const res = await fn();
      // 18+: 매 두 setState 매 single render
      setData(res);
      setLoading(false);
    } catch (e) {
      setError(e as Error);
      setLoading(false);
    }
  }

  return { data, loading, error, load };
}

Reducer alternative

const [state, dispatch] = useReducer(reducer, initial);
// 매 single dispatch 매 multi-field update — natural batching
dispatch({ type: 'SUBMIT_OK', payload: data });

Avoid stale closure with functional updates

// 매 sequential update — 매 함수형 사용
setCount(c => c + 1);
setCount(c => c + 1); // → +2, not +1

Measuring render with Profiler

import { Profiler } from 'react';

<Profiler
  id="Form"
  onRender={(id, phase, actual) => console.log(id, phase, actual)}
>
  <Form />
</Profiler>

매 결정 기준

상황 Approach
Multi-field update default (let batching work)
DOM measurement between updates flushSync
Sequential counter update functional updater
Complex state graph useReducer
Concurrent UI startTransition

기본값: do nothing — automatic batching handles it.

🔗 Graph

🤖 LLM 활용

언제: explain when batching applies, refactor pre-18 code, debug "why is render double" question. 언제 X: actual render count measurement — Profiler / DevTools.

안티패턴

  • 불필요한 flushSync: 매 performance 의 hurt — 마지막 수단.
  • Sequential setState with stale value: setCount(count+1); setCount(count+1) → +1.
  • Object identity reset: setData({...}) matter — same shallow ref skip.
  • Mid-render setState: trigger infinite loop.

🧪 검증 / 중복

  • Verified (React 18 RFC, React 19 docs).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — React 18+ batching pattern + flushSync