0
0
Astroframework~30 mins

When to hydrate vs keep static in Astro - Hands-On Comparison

Choose your learning style9 modes available
When to Hydrate vs Keep Static in Astro
📖 Scenario: You are building a simple product showcase page using Astro. Some parts of the page need to be interactive, like a button that shows an alert when clicked. Other parts are static and do not need any JavaScript on the client side.
🎯 Goal: Learn how to decide when to hydrate components for interactivity and when to keep components static in Astro. You will create a static product list and an interactive button that only hydrates when needed.
📋 What You'll Learn
Create a static product list component in Astro
Create an interactive button component that shows an alert on click
Use Astro's hydration directives to hydrate the button only on client
Keep the product list static with no client-side JavaScript
💡 Why This Matters
🌍 Real World
Websites often have parts that are static and parts that need interactivity. Knowing when to hydrate components helps build fast, efficient sites.
💼 Career
Front-end developers use hydration strategies to optimize performance and user experience in modern frameworks like Astro.
Progress0 / 4 steps
1
Create a static product list component
Create an Astro component called ProductList.astro with a products array containing these exact objects: { id: 1, name: 'Coffee Mug' }, { id: 2, name: 'Notebook' }, and { id: 3, name: 'Pen' }. Render an unordered list <ul> with each product name inside a <li>.
Astro
Hint

Use an array called products with the exact objects. Use {products.map(product => ( ... ))} to render the list.

2
Create an interactive button component
Create an Astro component called AlertButton.astro that renders a button with the text Click me. Add a client-side click event handler that shows an alert with the message 'Button clicked!'.
Astro
Hint

Define a function handleClick that calls alert('Button clicked!'). Attach it to the button's onClick event.

3
Hydrate the button only on client
In your main page Index.astro, import ProductList and AlertButton. Render <ProductList /> as static with no hydration. Render <AlertButton /> with the hydration directive client:load to hydrate it only on the client side.
Astro
Hint

Use client:load on <AlertButton /> to hydrate it only on the client. Render <ProductList /> normally.

4
Keep product list static with no client JavaScript
Verify that ProductList is rendered without any hydration directive so it stays static and does not load JavaScript on the client. Confirm that only AlertButton uses client:load hydration.
Astro
Hint

Do not add any hydration directive to <ProductList />. Only <AlertButton /> should have client:load.