Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Client directives

A client:* directive decides not only whether to bring an island to life but also when. The code of an island that is not visible right away can be loaded later, for example when the visitor scrolls to it. That keeps the first page load fast.

All directives

DirectiveWhen the island loads
client:loadRight after the page loads
client:idleWhen the browser has finished its main work and is idle
client:visibleWhen the element scrolls into view
client:media="(max-width: 700px)"When the media query matches
client:only="react"Only in the browser, no HTML during the build

client:visible

The Like button sits at the end of the post, and not everyone gets there. Change the directive in src/pages/posts/[id].astro:

<Content />
<LikeButton client:visible />

Open a post and the Network tab of the browser dev tools. Until you scroll to the button, no React code is loaded; when the button appears on screen, script files show up in the request list.

client:idle

For elements needed soon but not in the very first second, use client:idle. For example, a search field in the header in src/layouts/BaseLayout.astro:

---
import Search from '../components/Search.jsx';
---
 
<header>
  <a href="/">Anna's blog</a>
  <Search client:idle />
</header>

The field is visible right away as HTML and comes to life as soon as the browser is free. Search.jsx itself is an ordinary React component with an input.

client:only

Some components cannot run during the build: they access window or localStorage immediately. Such components get client:only with the library name:

<ThemeSwitcher client:only="react" />

Astro does not render their HTML on the server, and the spot stays empty until the script loads. The library name tells Astro how to render the component in the browser.

Server islands

Astro 5 also has server islands, the server:defer directive. It postpones rendering a slow .astro component on the server: the page is sent right away, and that piece is loaded by a separate request. It needs on-demand rendering with an adapter, covered in the "Data and server" chapter.

Common mistake

People put client:load on every component "just in case". The page loses Astro's main advantage and loads as much JavaScript as an ordinary React app. Give a directive only to components that respond to the visitor's actions, and choose the latest suitable one, most often client:visible or client:idle.

Thanks for reading!

Donate to the site — we work hard for you.