Demonstrating Astro Hydration with a Simple 2048 Game

I recently built a simple version of the classic 2048 game using the Astro web framework. Beyond being a fun exercise, this project provides a clear demonstration of Astro’s component hydration capabilities, specifically using the client:visible directive.

The core idea is to show how an interactive component, like this game, can be integrated into an otherwise static Astro page and brought to life in the browser.

What is Astro Hydration?

Astro is known for its “Islands Architecture,” where UI components are treated as isolated “islands” within a sea of static HTML. By default, Astro components render to HTML and ship zero client-side JavaScript.

However, for components that require interactivity (like our 2048 game), Astro needs to “hydrate” them – loading and running their necessary JavaScript in the browser. Astro offers several client:* directives to control when and how this hydration occurs.

Implementing the 2048 Game Component

For this 2048 game, I created an Astro component Game2048.tsx. To make it interactive, I used the client:visible hydration directive when including it on the page:

<!-- Example usage in an Astro page -->
<Game2048 client:visible />

The client:visible directive tells Astro:

  • Initially render the component as static HTML on the server.
  • Wait until the component enters the user’s browser viewport.
  • Once visible, load the component’s associated JavaScript and hydrate it, making it fully interactive.

This strategy balances performance (deferring JS loading) with user experience (making the game interactive when the user sees it).

Play the Game

Here is the interactive 2048 game component, loaded using client:visible. Try playing a round!

2048

2
2

Next Steps

This example provides a practical look at client:visible. When I have more time, I plan to write a more comprehensive introductory post delving deeper into Astro’s various hydration strategies and how to choose the right one for different use cases. For now, I hope this game serves as a helpful illustration.