What is client:only in Astro: Explanation and Usage
client:only in Astro is a directive that tells Astro to load and render a component only on the client side, skipping server rendering. It is used to include interactive components that depend on browser APIs or JavaScript without running them during server-side rendering.How It Works
Imagine you have a toy that only works when you hold it in your hand, not when it's in a box. client:only works similarly by telling Astro to keep a component packed away during server rendering and only bring it out when the page loads in the browser.
This means Astro will skip rendering that component on the server and instead load it dynamically on the client side. This is useful for components that need browser features like event listeners or animations that don't work on the server.
Behind the scenes, Astro generates code that loads the component's JavaScript only in the browser, improving performance and avoiding errors from trying to run browser-only code on the server.
Example
This example shows how to use client:only to load a React component only on the client side in an Astro page.
--- import Counter from '../components/Counter.jsx'; --- <html lang="en"> <head> <title>Client Only Example</title> </head> <body> <h1>Counter with client:only</h1> <Counter client:only /> </body> </html>
When to Use
Use client:only when you have components that rely on browser-only features like window, document, or user interactions that can't run on the server.
Examples include interactive maps, sliders, video players, or any React/Vue/Svelte components that need to run JavaScript in the browser.
This helps avoid errors during server rendering and improves page load by not sending unnecessary JavaScript to the server.
Key Points
client:onlydisables server rendering for a component.- It loads the component only in the browser after the page loads.
- Ideal for interactive or browser-dependent components.
- Helps prevent server-side errors from browser-only code.
- Improves performance by deferring JavaScript loading.
Key Takeaways
client:only tells Astro to render a component only on the client side, skipping server rendering.