Ark UI Logo
Guides
Component state

Component State

Learn how to manage component state using Context and Provider components.

Context Components

Context components expose state and functions to child components. In this example, Avatar.Fallback renders based on loaded state.

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" alt="avatar" />
  </Avatar.Root>
)

Good to know (RSC): Due to the usage of render prop, you might need to add the 'use client' directive at the top of your file when using React Server Components.

Provider Components

Provider components can help coordinate state and behavior between multiple components, enabling interactions that aren't possible with Context components alone. They are used alongside component hooks.

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 (
    <>
      <button onClick={() => accordion.setValue(['maintainers'])}>Set to Maintainers</button>

      <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>
    </>
  )
}

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.',
  },
]

When using the RootProvider component, you don't need to use the Root component.

See more in Examples.