useSlots
React children에서 이름 붙은 slot 컴포넌트를 추출하는 훅이에요. Primer의 slot 기반 복합 컴포넌트를 구동해요. 현재 Primer 내부 전용(internal surface)이며 @primer/react에서 재수출되지 않아요. [slots, rest] 튜플을 반환해서, 설정한 slot 이름과 일치하는 children과 나머지 children을 나눠줘요.
출처: 문서
본문
children에서 이름 붙은 slot 컴포넌트를 추출해요. Primer의 slot 기반 복합 컴포넌트를 구동해요.
useSlots는 현재 Primer 내부 전용(internal surface)이고 @primer/react에서 재수출되지 않아요. 이 페이지는 동작 방식을 문서화한 것인데, slot 사용처(PageLayout, PageHeader, ActionList, FormControl)를 읽을 때 이 알고리즘을 알면 훨씬 쉬워지기 때문이에요. 이 훅을 자신의 코드에서 써보고 싶다면 Primer issue를 열어서 export를 논의하세요. 대부분의 사용 사례는 훅을 직접 건드리지 않고 extending components 가이드의 패턴으로 해결돼요.
useSlots는 React children 컬렉션을 순회하면서 두 그룹으로 나눠요: config에서 이름 붙은 slot과 일치하는 children, 그리고 그 외 나머지.
시그니처
function useSlots<Config extends SlotConfig>(
children: React.ReactNode,
config: Config,
): [Partial<SlotElements<Config>>, React.ReactNode[]]
| 인자 | 타입 | 설명 |
|---|---|---|
children |
React.ReactNode |
검사할 children. 보통 복합 컴포넌트의 children prop이에요. |
config |
SlotConfig |
slot 이름과 일치시킬 컴포넌트의 매핑. matcher styles를 참고하세요. |
[slots, rest] 튜플을 반환해요.
| 반환 | 타입 | 설명 |
|---|---|---|
slots |
Partial<{[name]: ReactElement}> |
config의 slot 이름마다 하나의 항목을 가진 객체예요. 일치하는 child를 찾을 때까지 각 항목은 undefined이고, 찾으면 그 ReactElement가 돼요. |
rest |
React.ReactNode[] |
어떤 slot과도 일치하지 않은 모든 children을 원래 순서대로 담아요. |
예제
import {useSlots} from '@primer/react/hooks' // internal import path
import {ActionList} from '@primer/react'
function StatusRow({children}) {
const [slots, rest] = useSlots(children, {
leadingVisual: ActionList.LeadingVisual,
description: ActionList.Description,
})
return (
<li>
{slots.leadingVisual}
<span>{rest}</span>
{slots.description}
</li>
)
}
// Consumer
<StatusRow>
<ActionList.LeadingVisual>✅</ActionList.LeadingVisual>
Approved
<ActionList.Description>Status detail</ActionList.Description>
</StatusRow>
ActionList.Item은 내부에서 같은 패턴을 사용해요. 더 많은 slot(trailingVisual, trailingAction 등)을 설정하고 더 정교한 레이아웃으로 렌더링할 뿐이에요.
Matcher 스타일
config 객체의 각 항목은 두 가지 형태를 가질 수 있어요.
1. 컴포넌트 참조
가장 간단한 형태예요. child.type === Component 또는 child.type.__SLOT__ === Component.__SLOT__이면 일치해요.
useSlots(children, {
visual: LeadingVisual,
description: Description,
})
2. 컴포넌트 + 조건자 (predicate)
[Component, (props) => boolean] 튜플 형태예요. 컴포넌트 검사가 먼저 실행되고, 일치하면 조건자가 child의 props에 대해 실행돼요. 하나의 컴포넌트가 variant에 따라 서로 다른 slot 위치로 렌더링되는 상황에 유용해요.
useSlots(children, {
block: [Description, props => props.variant === 'block'],
inline: [Description, props => props.variant !== 'block'],
})
일치(matching) 동작 방식
각 child를 순서대로 처리해요.
- 유효한 React element가 아니면 건너뛰어요(문자열, 숫자,
false등은 바로rest로). - 모든 설정된 slot이 이미 채워졌다면
rest로 밀어 넣고 계속해요. dev 모드에서는 child가 이미 채워진 slot과 일치했을지도 검사하고, 그렇다면 중복 slot 경고를 내보내요. - 그 외에는 config를 순회하며 일치 항목을 찾아요. 찾으면 child를
slots[name]에 저장하고, 못 찾으면rest로 밀어 넣어요.
slot 조회는 먼저 일치하는 것이 우선(first-match-wins)이에요. 두 child가 같은 slot과 일치하면 첫 번째만 유지하고 두 번째는 버려요(dev 경고와 함께).
성능 특성
useSlots는 child마다가 아니라 복합 컴포넌트가 렌더링될 때마다 한 번 호출돼요. child 하나당 작업은 최악의 경우 O(slots)이고, 모든 slot이 채워지면 O(1)이에요. 이는 수백 개 항목을 렌더링할 수 있는 ActionList 같은 목록 컴포넌트에서 중요해요.
이 훅은 일반 객체를 반환하지 않고, memoize된 참조를 반환하지 않아요. slots.x를 useEffect 의존성 배열에 넣는다면 매 렌더링마다 바뀐다고 기대해야 해요.
관련
- Extending components 가이드 —
asprop, slot 시스템, 래핑 패턴, 새 slot 작성. SlotMarker타입 —@primer/react에서 export되며 컴포넌트를 slot-capable로 타입 지정하게 해줘요.
더 알아보기 (Learn more)
useSlots(children, config)는[slots, rest]를 돌려줘요 — slot은 config에 이름 붙은 것과 일치하는 요소들이에요.- matcher는 컴포넌트 참조 또는
[Component, predicate]튜플 두 형태를 지원해요. - 내부 전용 훅이라
@primer/react에서 export되지 않아요. 보통은 extending components 가이드 패턴으로 충분해요. - slot 조회는 first-match-wins이고, 복합 컴포넌트는 렌더링마다 한 번 호출돼요.