본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

컴포넌트 상태

원문 보기 위키 갱신

컴포넌트 상태 (Component State)

Context와 Provider 컴포넌트를 사용해서 컴포넌트 상태를 관리하는 방법을 배워봐요. 컴포넌트의 상태가 필요할 때 세 가지 옵션 중 상황에 맞는 방법을 선택할 수 있어요.

출처: 문서

본문

컴포넌트의 상태에 접근해야 하나요? 세 가지 옵션이 있어요.

접근 방식 (Approach) 언제 쓰면 좋을까요 (When to use it)
Component.Context 렌더 prop(render props)을 통한 빠른 인라인 접근
use*Context 훅 상태를 읽는 커스텀 자식 컴포넌트를 만들 때
useComponent + RootProvider 외부에서 컴포넌트를 제어할 때

Context 컴포넌트 (Context Components)

Component.Context를 사용하면 렌더 prop을 통해 상태에 인라인으로 접근할 수 있어요. 아래는 Avatar.Fallback이 loaded 상태를 읽어 서로 다른 콘텐츠를 보여주는 예시예요.

알아두면 좋아요 (RSC): 렌더 prop 패턴은 React Server Components를 사용할 때 'use client' 디렉티브가 필요해요.

import { Avatar } from '@ark-ui/react/avatar'
import styles from 'styles/avatar.module.css'

export const Context = () => (
  <Avatar.Root className={styles.Root}>
    <Avatar.Context>
      {(avatar) => <Avatar.Fallback className={styles.Fallback}>{avatar.loaded ? 'PA' : 'Loading'}</Avatar.Fallback>}
    </Avatar.Context>
    <Avatar.Image className={styles.Image} src="https://i.pravatar.cc/300?u=a" alt="avatar" />
  </Avatar.Root>
)

Context 훅 (Context Hooks)

모든 컴포넌트는 use*Context 훅(useDialogContext나 useMenuContext 같은)을 내보내요. 어떤 자식 컴포넌트에서든 이 훅을 호출하면 렌더 prop 없이도 상태와 메서드에 접근할 수 있어요.

import { Dialog, useDialogContext } from '@ark-ui/react/dialog'

function CustomCloseButton() {
  const dialog = useDialogContext()
  return <button onClick={() => dialog.setOpen(false)}>Close ({dialog.open ? 'open' : 'closed'})</button>
}

export const Demo = () => (
  <Dialog.Root>
    <Dialog.Trigger>Open</Dialog.Trigger>
    <Dialog.Content>
      <CustomCloseButton />
    </Dialog.Content>
  </Dialog.Root>
)

이 훅은 Component.Context와 동일한 API를 반환하되, 중첩 구조만 제외한 거예요.

Provider 컴포넌트 (Provider Components)

컴포넌트 트리 바깥에서 컴포넌트를 제어해야 하나요? useComponent 훅(useDialog 같은)을 RootProvider와 함께 사용하면 돼요.

RootProvider를 사용할 때는 Root 컴포넌트는 건너뛰어요. 둘 다 필요하진 않아요.

import { Accordion, useAccordion } from '@ark-ui/react/accordion'
import { ChevronDownIcon } from 'lucide-react'
import styles from 'styles/accordion.module.css'

export const RootProvider = () => {
  const accordion = useAccordion({
    multiple: true,
    defaultValue: ['ark-ui'],
  })

  return (
    <div className="stack">
      <output>Value: {JSON.stringify(accordion.value)}</output>

      <Accordion.RootProvider className={styles.Root} value={accordion}>
        {items.map((item) => (
          <Accordion.Item className={styles.Item} key={item.value} value={item.value}>
            <Accordion.ItemTrigger className={styles.ItemTrigger}>
              {item.title}
              <Accordion.ItemIndicator className={styles.ItemIndicator}>
                <ChevronDownIcon />
              </Accordion.ItemIndicator>
            </Accordion.ItemTrigger>
            <Accordion.ItemContent className={styles.ItemContent}>
              <div className={styles.ItemBody}>{item.content}</div>
            </Accordion.ItemContent>
          </Accordion.Item>
        ))}
      </Accordion.RootProvider>
    </div>
  )
}

const items = [
  {
    value: 'ark-ui',
    title: 'What is Ark UI?',
    content: 'A headless component library for building accessible web apps.',
  },
  {
    value: 'getting-started',
    title: 'How to get started?',
    content: 'Install the package and import the components you need.',
  },
  {
    value: 'maintainers',
    title: 'Who maintains this project?',
    content: 'Ark UI is maintained by the Chakra UI team.',
  },
]

올바른 접근 방식 고르기 (Choosing the Right Approach)

  • Component.Context — 조건부 렌더링을 위한 빠른 인라인 접근
  • use*Context 훅 — 부모 상태가 필요한 재사용 가능한 자식 컴포넌트를 만들 때
  • useComponent + RootProvider — 외부에서 동작을 트리거할 때 (메뉴 항목에서 다이얼로그를 여는 것처럼)

더 알아보기 (Learn more)