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'

export const Context = () => (
  <Avatar.Root>
    <Avatar.Context>{(avatar) => <Avatar.Fallback>{avatar.loaded ? 'PA' : 'Loading'}</Avatar.Fallback>}</Avatar.Context>
    <Avatar.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.

import { Accordion, useAccordion } from '@ark-ui/react/accordion'
import { ChevronDownIcon } from 'lucide-react'
import { useState } from 'react'

export const RootProvider = () => {
  const [value, setValue] = useState(['React'])
  const accordion = useAccordion({
    multiple: true,
    value,
    onValueChange: (e) => setValue(e.value),
  })

  return (
    <>
      <button onClick={() => accordion.setValue(['Vue'])}>Set to Vue</button>

      <Accordion.RootProvider value={accordion}>
        {['React', 'Solid', 'Vue'].map((item) => (
          <Accordion.Item key={item} value={item}>
            <Accordion.ItemTrigger>
              What is {item}?
              <Accordion.ItemIndicator>
                <ChevronDownIcon />
              </Accordion.ItemIndicator>
            </Accordion.ItemTrigger>
            <Accordion.ItemContent>{item} is a JavaScript library for building user interfaces.</Accordion.ItemContent>
          </Accordion.Item>
        ))}
      </Accordion.RootProvider>
    </>
  )
}

See more in Examples.