---
type: snippet
tags: [react, children, pattern, compound-component]
status: release
ctime: 2025-12-21
mtime: 2026-01-27
---

React Children API - 가능하지만 비추천

> [!WARNING]
>
> 암묵적 의존성, 타입 안전성 부족, 매 렌더 트리 순회, 예측 불가능

## 재귀 순회

```tsx
function traverseReactNode(children: ReactNode, callback, typeToMatch?) {
  Children.forEach(children, (child) => {
    if (!isValidElement(child)) return
    if (child.type === Fragment) {
      traverseReactNode(child.props.children, callback, typeToMatch)
      return
    }
    if (child.type === typeToMatch) callback(child)
    if (child.props?.children) {
      traverseReactNode(child.props.children, callback, typeToMatch)
    }
  })
}
```

## 동적 래핑

```tsx
const renderChildren = (children) => {
  const elements = React.Children.toArray(children)
  const hasLink = elements.some(
    (el) => React.isValidElement(el) && el.props.url
  )
  return hasLink ? children : <ul>{children}</ul>
}
// toArray는 string, number도 포함 → isValidElement 체크 필수
```

## 대안: Compound Component

```tsx
// ❌ 마법처럼 동작 (예측 불가)
<Tabs>{/* 어디에 넣든 Tab 찾아줌 */}</Tabs>

// ✅ Compound Component
<Tabs.Root>
  <Tabs.List>
    <Tabs.Trigger value="a">A</Tabs.Trigger>
  </Tabs.List>
  <Tabs.Content value="a">Content</Tabs.Content>
</Tabs.Root>
```

React 팀도 2021년부터 Children API 사용 권장하지 않음: "Using Children is uncommon and can lead to fragile code"

역사적 배경: 2013년엔 Context API도 없었음. "선언형"이라면서 Children API로 명령형 트리 순회 제공하는 이중성.

---

- [react-children-utilities](https://github.com/fernandopasik/react-children-utilities) - deepMap, deepFind, deepFilter
