How to Use Client Directives in Astro for Interactive Components
In Astro, use
client directives like client:load, client:idle, client:visible, and client:media to control when and how components load on the client. Add these directives as attributes to your component imports to enable client-side interactivity only when needed.Syntax
Client directives are added as attributes to Astro component imports to control their hydration behavior on the client side.
Common directives include:
client:load- Hydrates the component immediately after page load.client:idle- Hydrates when the browser is idle.client:visible- Hydrates when the component scrolls into view.client:media="(min-width: 768px)"- Hydrates based on a media query.
astro
<MyComponent client:load />
Example
This example shows how to use client:load to hydrate a button component that increments a counter when clicked.
astro
--- import CounterButton from '../components/CounterButton.jsx'; --- <html lang="en"> <head> <title>Astro Client Directive Example</title> </head> <body> <h1>Counter with client:load</h1> <CounterButton client:load /> </body> </html> // components/CounterButton.jsx import { useState } from 'react'; export default function CounterButton() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
Output
<h1>Counter with client:load</h1>
<button>Count: 0</button>
Common Pitfalls
Common mistakes when using client directives include:
- Forgetting to add a client directive, causing components to render static HTML without interactivity.
- Using
client:loadunnecessarily, which can slow page load if many components hydrate immediately. - Not matching the directive to the use case, e.g., using
client:loadwhenclient:idleorclient:visiblewould be more efficient.
astro
--- import CounterButton from '../components/CounterButton.jsx'; --- <!-- Wrong: no client directive, button won't be interactive --> <CounterButton /> <!-- Right: add client directive to enable interactivity --> <CounterButton client:load />
Quick Reference
| Directive | Description | When to Use |
|---|---|---|
| client:load | Hydrates component immediately after page load | For essential interactive components |
| client:idle | Hydrates when browser is idle | For non-critical components to improve performance |
| client:visible | Hydrates when component scrolls into view | For components below the fold or offscreen |
| client:media="(query)" | Hydrates based on media query match | For responsive behavior based on screen size |
Key Takeaways
Add client directives like
client:load to Astro components to enable client-side interactivity.Choose the right directive to balance performance and user experience.
Without a client directive, components render static HTML without interactivity.
Use
client:visible or client:idle to defer hydration and improve page speed.Client directives accept media queries for responsive hydration control.