Guides
Component state

Component State

Learn how to access the state of a component using Context and Provider components.

Motivation

Effectively accessing and managing component state is crucial for dynamic UIs in Ark. Using Context and Provider components, you can write modular, maintainable code. This guide shows how to share state and behavior across your application, enabling flexible and powerful component compositions.

Context Components

Context components allow you to access a component's state or functions from a child component. In the example below, Avatar.Fallback conditionally renders based on the loaded state.

import { Avatar } from '@ark-ui/solid/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 { Avatar, useAvatar } from '@ark-ui/solid/avatar'

export const Provider = () => {
  const avatar = useAvatar({
    onStatusChange: (e) => console.log('status changed', e),
  })

  return (
    <Avatar.RootProvider value={avatar}>
      <Avatar.Fallback>PA</Avatar.Fallback>
      <Avatar.Image src="https://i.pravatar.cc/300" alt="avatar" />
    </Avatar.RootProvider>
  )
}

For more examples of composing components with Context and Provider components, visit our Examples section.