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.

<script setup lang="ts">
import { Avatar } from '@ark-ui/vue/avatar'
</script>

<template>
  <Avatar.Root>
    <Avatar.Context v-slot="avatar">
      <Avatar.Fallback>
        {{ avatar.loaded ? 'PA' : 'Loading' }}
      </Avatar.Fallback>
    </Avatar.Context>
    <Avatar.Image src="https://i.pravatar.cc/300" alt="avatar" />
  </Avatar.Root>
</template>

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.

Example not found

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