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.
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.
import { Avatar } from '@ark-ui/react/avatar'
import styles from './index.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>
)
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.
When using the
RootProvidercomponent, you don't need to use theRootcomponent.
import { Accordion, useAccordion } from '@ark-ui/react/accordion'
import { ChevronDownIcon } from 'lucide-react'
import styles from './index.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.',
},
]