Extending React Using Astro

Rate this content

We'll start out by taking a look at Astro; What is Astro, why does it exist and what problems does it solve. How can we optimise our React application / components by using Astro? Let's do some live coding and start out exploring Astro in combination with React! 

Main talking points: 

- What is Astro 

- Astro integrations 

- React in Astro 

- Partial Hydration 

- Server Side Rendering vs Server Side Generation

24 min
06 Jun, 2023

Video Summary and Transcription

Astro is an all-in-one framework built for speed that allows for flexibility and customization. It supports file-based routing, dynamic pages, and easy integration with popular frameworks like React. Astro's client directives enable selective hydration and optimization of websites. It also supports fetching data from APIs and using Markdown. With features like style preprocessors, CSS support, and deployment adapters, Astro stands out as a framework for SEO, developer experience, and performance.

Available in Español

1. Introduction to Astro

Short description:

Hey everyone, thanks for tuning in! I'm Elion, a software engineer at Veebridge in Belgium and an Astro Ambassador and Maintainer. Today, I'll introduce you to Astro, an all-in-one framework built for speed. We'll explore the Astro Island architecture and how it can be used with React. Let's start with a theoretical example. In Astro, you can bring your own framework, allowing for flexibility and customization. Check out Astro's website for all the official and unofficial integrations. Stay tuned for the React integration in the following slides!

Hey everyone, and thanks for tuning into my talk for React Semi 2023. I'm Elion, I'm a software engineer at Veebridge in Belgium, and for a short while I've also been an Astro Ambassador and now I'm also an Astro Maintainer.

And today I'm going to tell you about Astro. So if you do want to follow me online, or reach out to me if you have any questions, you can do that with at ElionCodes, I'm most active on Twitter, so that would be the easiest, but feel free to reach or contact me anywhere you find me on, okay.

So now that you know who I am, let's start by the question of this whole talk, which is, what is Astro? Well, Astro isn't just like a lightning-fast framework, it's actually even better than those blazingly fast ones. I'd like to call it astronomically fast. So in short, Astro is this all-in-one framework built for speed, and that might sound as an empty box right now, but I promise you that it will get clearer over the following slides why I say that.

So, my goal for today is to introduce you to the Astro Island architecture, and show you how it can be used with React, so you'll be extending React with Astro's capabilities. So, let me start out by showing you a theoretical example. So, take this page for instance. We can divide all of these HTML structures in blocks, see it as a Lego baseplate? With blocks added on the baseplate, and on that blocks, little blocks, and totally, you get the point.

So, we already do this in a couple of frameworks out there. Well, most UI frameworks actually, being Dittsveld, Vue, Solider, React. We are familiar with this component design. But in Astro, you can actually do something like this. Well, it's theoretically possible, not recommended, it will become clear why. But you can choose different colors or flavors for each brick, so referring to the color as being the UI framework. For instance, if you want a component to be solid JS for instance, or you want to component in Svelte, you can do it with Astro. So, that's why we call Astro a bring your own framework. So, Astro is actually a framework that makes it able for you to bring your own framework onto it which means that you can bring it and I'll show you that in the following slides. For instance, all the integrations can be checked out on Astro's website itself. There is a full page dedicated to all integrations, all official and unofficial existing integrations. And, as you can see, you tuned in for an event that's mainly about React. So, I will show you what React integration looks like in the following slides. But, before we dive into React with Astro, we of course have to start a new Astro project. So, let me pop into the terminal here and show you what our CLI looks like. So, you can use any package manager you like. I'd like to use pnpm. But feel free to use npm or Yarn. So, you just create a new thing and then you see Houston.

2. Setting up a New Project and Astro File Structure

Short description:

Houston, our mascot, will guide us through setting up a new project in Astro. We'll answer a few questions, install dependencies, and consider TypeScript. Once set up, we can open the project in VS Code, with support for Astro files. The syntax is similar to HTML with some JSX. Before diving into coding examples, let's explore the Astro file structure, which is similar to other meta frameworks like Next or Nuxt. Astro supports file-based routing and dynamic pages.

Yeah, there he is. So, Houston is our mascot and they will guide us through the process of setting up a new project inside of our terminal. So, he will ask you a couple of questions. For instance, what's your project? Do you want to use a template? Which I don't. And then of course, it will install your dependencies and ask you if you'd like to use TypeScript.

So, while we wait, even if you don't use TypeScript or don't like, well, if you don't want to use TypeScript or write your own TypeScript, well, Astro will actually still be using some TypeScript on the backend, which you won't have to worry about, but know that there is still some typesafety going on. So, I'll choose strict here just because to show you how it works and stuff. Okay, cool. So, that's how easy it is to set up a new project in Astro. Really cool.

So, maybe let's open up our project in VS Code. So, yep, there we go. So, to get support for the Astro files in VS Code, you still have to install a separate extension. It's a very good integration, it's official, so don't worry about it. Everything else should work out of the box. But as you can see, let's take a look at the syntax here. So, the syntax feels quite familiar. It looks like something in between. Well, actually, it looks just like regular HTML with some bits and pieces of JSX in between. But most of what we can see right now is HTML. But I'll go into that a little bit later.

Because before we dive into our coding examples, I want you to take a look at our Astro file structure, because it's very important to know what Astro is capable of. There's nothing too weird going on here. Your configuration happens in the astro.config.js file. Your components and pages and layouts go in their separate directories inside of the source folder. That all should make sense if you ever used a meta framework like Next or Nuxt before. Astro has file-based routing, so every file inside of the pages folder will respond to its own page or route. You can see there is inside of the blog an id in between brackets there that's a dynamic page, so it's fully capable of doing that as well. And also we have the 404 page. But as you can see, there is also like a little hint to the component there, which is called counter.tsx.

3. Adding React Integration

Short description:

Let's add the React integration into our project. We can use React components inside of Astro. The 'astro as react' command updates files and installs dependencies. It's a cool CLI experience and better than Create React App.

I'll show you that in a couple of minutes. So let's add the React integration into our project. So that we can use React components inside of Astro. When you type astro as react, which I've done here, it will show you what files that command will update. It will show you what dependencies it will install. As you can see, it's just like the latest React and React DOM and then the integrations itself. So very cool. It's a very cool and good CLI experience. It's very awesome and this is what I like to think of the better CRA, which is called, Create React Astro. Way better than Create React App because it's based on Vite, of course. Okay.

4. Building React Components with Astro

Short description:

Astro provides an amazing developer experience with easy integration of popular frameworks and tools. The updated config file automatically imports and installs React integration. We can start building React components by creating a new counter.tsx file. The Astro compiler recognizes tsx or gsx extensions as React components. We can even copy-paste components from other websites or projects into Astro without any hassle.

So this is also a good point to show you how amazing the developer experience with Astro is. You can just type astro add and it will automatically show you a list of popular integrations. So you have the UI frameworks listed there. You have a couple of SSR, adapters, and of course, some other stuff like Tailwind, for instance. So from CLI to error pages, Astro always got some great developer experience because it's very important to us.

Okay. So this is the updated config file. We just imported React integration and added into our integrations list there- well, in the array, actually. And all of that went automatically- well, automagically, even, without any hassle. So really cool.

Okay. So now that we imported and installed our React integration, we can actually start out by building React components. So let's just dive in and do that. To start building with React and Astro, we can simply just create a new component, which we call counter.tsx. When you use tsx or gsx extension, the Astro compiler will automatically know that you're referring to a React component.

As you can see, I'm just writing a basic React counter. We have probably all done this a couple of times, so I probably don't need to explain everything. But it's just a basic, simple function in React. Returning some HTML where we're going to use some states. We're going to have two buttons, one that increases the state number and one that decreases the state number. And I'm just going to type here how we define that state. And as you can see, I'm going to remove the React here and just import the state from React. And this actually is way cooler than you might think at first. Because, actually, we're using this component in Astro, but still, we're actually importing the state from the React library itself. We're not importing it from the React Astro integration. That basically means that you can just copy-paste components over from, for instance, an XJS website or an old create React website. You can just copy and paste those components over right into Astro, and they will work. How cool is that? So, yeah, really cool thing. Most packages also will work. Well, most, not all of them.

5. Adding React Fibre and Partial Hydration

Short description:

React Fibre works with Astro. To add the counter component to the page, import it in the index.astro file. Astro doesn't ship JavaScript by default, but it supports interactivity through partial hydration. Partial hydration is like watering a plant; if not enough is done, the plant feels sad and simple.

But, for instance, React Fibre will also work with Astro. So that's a cool thing to note as well.

Okay, so now that we build our counter component, we still have to add it onto our page, of course. So we can just head back to our index.astro, which will just be the index page, and we can actually see the brackets on top there. Well, the code fences. We can just import it like we would regularly do with JavaScript, set it on the page. And if we now head to our dev server, which is localhost 3000, of course, you can see it's actually there on the page. Now, you can see I'm hovering over those buttons. I'm actually clicking on it, but you can't see that, of course. But the state is not updating. So that's something weird going on there now, is it?

Well, actually, this is wanted behavior. Astro ships no JavaScript at all by default. So let's take another look at that. So if we open up our browser tools here, I'm going to click on one more time so you can see it. I'm going to open our browser dev tools. Well, if we head to our network tab and refresh, you can see there is nothing at all being shipped except for HTML. That is crazy. So of course, what if you need interactivity? What if you want interactivity on your website? Or what if you do want to render your components conditionally, or have updating components? Well, of course it's possible inside of Astro. It's not that it's completely server side generated. It's possible, and we call it partial hydration. Let me load in the assets here. They kind of flip out, but it's supposed to represent a swimming pool inside of the leather. It's OK, it's better right now. OK, cool. So but I hear you thinking, what is partial hydration? That term doesn't make sense. Well, over the times that I've done this talk, I've done it a couple of times, I've perfected like the perfect analogy for it. It's actually this plant. So partial hydration, of course, we hydrate plants. And if we don't water or hydrate our plant enough, our plant will feel very sad. It will feel simple.

6. Hydration with Astro's Client Directive

Short description:

In Astro, we can selectively choose which components should use JavaScript and control when they become interactive. Astro offers different options for hydration, such as client idle and client load. By using the client directive, we can ship JavaScript only to the components that require interactivity. Let's take a closer look at the client load directive and how it works.

It will feel boring. If we hydrate it too much, our plant will drown in water. Or if we take it to our application, we'll be drowned in like technical debt, bundle size, or general complexity. So, yeah, let's take a theoretical look at this into an actual example.

So imagine we have this page in like a normal JavaScript meta framework. Think Next or Nuxt or even Svelte for that matter. All of these different components here will require JavaScript to render, even though some of them might not even need interactivity, for instance. Look at the footer. It's basic links. It's maybe an image. Why do we need JavaScript if we don't actually need it? This is not the way the web is supposed to work.

So in a perfect world, we actually want something more like this. Or we just select our components that we want to be interactive and then ship JavaScript just to those little components. And actually this is something that Astro can do. So in Astro you can do this with the client directive, which I've shown you here. Using the client directive, we can choose which components should use JavaScript, but we also have the flexibility to control how or when our components should become interactive. And of course, I'm going to showcase that to you. So we have a couple of options for hydration and let's take a look at most of them. So client idle makes sense. It will only start hydrating your component as soon as your main browser thread becomes free. Very useful and it's probably the one I'll be using on all of my components. Except for client visible ones, but you'll see. So I'm going to be demoing this one as well so you can actually see what it does. So client load is just like what it says, it will start hydrating your component as soon as it can. Okay, so let's take a look at client load directive. If we add it just here to our counter component, which is the same one we've actually done before, I'm going to open up my terminal here and going to build and preview it. And the reason that I'm doing that is actually because I want you to see like the actual shipped result. Because of course, if I use the dev server, Vite will ship some JavaScript by default, which all makes sense. But now you can see that like we have a couple of JavaScript files and which it, yeah, exactly. Now it works.

7. Hydration with Client Directives

Short description:

The counter component is fully functional as a React component inside of Astro. Client media is a directive perfect for mobile or tablet components, allowing hydration based on media queries. Client-visible is a powerful directive that imports JavaScript when the component enters the viewport. Let's trade client-load for client-visible to see its effect. The JavaScript is instantly visible when scrolling, and the counter element hydrates instantly. Let's explore our theoretical web application further.

So you could see, there is like one that says counter.jsx blah blah blah. So that's the one that actually make sure that your component is hydrated. So the counter is fully functional as a React component inside of Astro. Really cool.

Okay. Then we have client media. Client media is a very cool directive. It's perfect for like mobile only components or tablet components. It will let you start hydrating when the given media queries meet. Makes sense.

There is also client-visible. Like I saw, I told you before, it's a very powerful one. It will only start importing your JavaScript as soon as the component enters the viewport. It uses the intersection observer for that. So let's trade in the client-load here by client-visible, so you can see what it does. Let me also add a couple of text because if it's visible instantly, you won't see any difference. I'm copy and pasting these a few times over instead of using an image shortcut. I know. I'm very sorry. I'm very bad at coding live. Although this is pre-recorded.

Okay, so let me go and start the build again. You can see our builds are very fast, so I don't really care that I leave this in. Okay, we're in the browser. The moment we start scrolling down, you can see, bam, there is our JavaScript there. Super cool. The moment the counter element comes in, it instantly hydrates. And of course, fully functional as well, which does make sense. Awesome. Let's take another look at our theoretical web application.

8. Optimizing Website with Client Directives

Short description:

Now that we have a better understanding of client directives, let's optimize our website. We'll start with the header, which requires interactivity. The client load directive is perfect for this, as it ships JavaScript as soon as the initial DOM content is loaded. The sidebar, on the other hand, can be deferred using the client visible directive. This ensures that heavy components like image carousels are only loaded when necessary. Astro's pure HTML components make it perfect for SEO without the need for excessive JavaScript. Check out our Astro hype meter to see the impressive lighthouse scores of Astro sites in production. Lastly, we'll explore fetching dynamic data, such as jokes, from an API.

Now that we have a better understanding of our client directives, we can perhaps make this website page example astronomically fast. Or astronomically optimized, even. So let's try together, let's think together. I know I don't have interactivity, but let's just think about it.

Let's start with the header. So the header is a component that is always at the top, requires some interactivity, like buttons for instance, theme switchers and such. So it makes sense for us to ship JavaScript to that first. So what client directive would we use for that? Probably you're thinking of client load, that would make sense. So you're spot on. So simply because the client load ships your JavaScript as soon as the initial DOM content is loaded, it's an important part here in the header of the overall UX and site experience, especially if you have a dark mode or even a mobile button or whatever.

So what about the sidebar on the left? The sidebar is only logical to like try and defer as much as possible because it's in a site. So for this, we have the client directive of course. Oh, and I see I was too fast. I already had the image carousel there, which is client visible. But let me explain to you why we use client visible there. Because it's an image carousel, it probably is a very heavy component to load. Maybe it's dependent on another library and maybe it has some animations. And all of those things would make probably would make sense to like ship only if you see that component because otherwise you're just slowing your whole page down just because some images that a user might never see. And that actually means that you no longer would be seeing this, but you would be seeing this, which is really cool.

The secret sauce to what makes us, this is the secret sauce actually, what makes Astro so perfect for SEO. All of the components are pure HTML, except if you like hydrate them and the content is fully indexable. So all of that ever without having to ship a ton of JavaScript. So that's what an Astro site gives you when you ship it to production. And actually you can see this real time on our Astro hype meter, whatever we have. It's a tool we have online where we measure like all the scores, lighthouse scores of all Astro sites in production. And it's crazy to see how many of them are like all four in the hundreds.

Okay. So I also have of course, a little demo of having dynamic data for instance. What if we want to have a jokes API? We want to fetch a joke from the API? So let me add the code fence and let me add the HTML. There we go.

9. Using APIs and Markdown in Astro

Short description:

We want a joke, and it's really easy with Astro. You can see the combination of JSX inside HTML, which is purely Astro syntax. When you refresh the page, the API won't be fetched due to Astro's static site generation. However, you can extract it into a component. Markdown in Astro supports client directives, allowing for interactive elements like the counter component. This opens up a lot of possibilities, such as fetching data from a CMS. Astro also prioritizes documentation.

We want a joke so we can just do, okay, here is the API, fetch it, set it up. And here is the joke. It's really easy. Note, also like the top level away they're really cool feature. Really awesome. You can also see here the combination of like JSX inside of the HTML which is purely Astra syntax. So it's really cool, really cool. You probably are used to it. It will feel like a second nature to you.

So if we now head to our browser and have in the jokes, you can see the jokes is they're displayed on the screen. Now, there is one side note to this. If I would refresh this page you would see that it doesn't fetch an API. That's because Astro is of course SSG by default. So it will only fetch the API once at build time, which also means that if you refresh this page a hundred times all of those hundred times will be the same exact API response without actually... Because you compile it basically down to HTML and just ship that HTML. So the joke will stay the same. Of course, there is a way around this. You could extract it into a component.

So we also have a great markdown story at Astro. We can add some texting markdown but you can also use MDX. And what's the cool thing about MDX is that you can also import a counter component. Of course, it doesn't work here and that's exactly because the same thing that I told you before is all compiled down to HTML. It won't ship any JavaScript by default. But the cool thing is that client directives are totally supported in markdown. Well, markdown extended so you can just go ahead and use it and then you'll see the counter now is interactive. So that's really cool for authoring content. You can do even whole pages in MDX without worrying about it. So what I've shown you I know is a little abstract but it opens up a lot of possibilities. For instance, you can fetch this data from a CMS and so on. Of course, we also try to document as much as possible with Astro.

10. Astro's Features and Advantages

Short description:

Astro offers easy integrations with style preprocessors, CSS support, Denoise runtime, prefetch package, image integration, Tailwind CSS integration, offloading JavaScript with Party Town or Cloudflare web workers, deployment adapters for Vercel and Netlify, hybrid rendering, and building API endpoints. Astro stands out as the ultimate framework for SEO, developer experience, and performance. Most HTML is rendered at build time, making it crawler-friendly. Try Astro at astro.new, explore the amazing documentation, and join the support community at astro.build.chat. Thanks for watching!

So we actually are working with the front matter team for now to also like add a new CMS guide for instance. You can find all of them on the Astro documentation.

So of course, my time is almost up. So this is also not everything that Astro offers. Astro also has easy integrations with style preprocessors. For instance, it's just as easy as NPM install SAS for instance and it just works because Astro has both CSS support. Astro also supports Denoise a runtime. There is also first class prefetch package. There is an image integration to optimize and style your images. Of course, there is also Tailwind CSS integrations. If you want to offload all of your JavaScript of the main thread, you can use Party Town or Cloudflare web workers. Deployment adapters for instance for Vercel, Netlify and so on. You can even use the same ones with SSR as well. And since Astro version 2, there is also the possibility to use hybrid rendering or build API endpoints into your Astro project. Also, very cool as well. And then of course, there is content collections but content collections would be a whole other topic for a talk because it would take way too many time.

Cool, so now that you have seen some of Astro's features and architecture advantages, why should you use Astro? Why would you not prefer Astro for other META frameworks like Next, Nuxt, Solid Start, whatever? All of those examples make Astro, all of the previous examples actually, make Astro like the ultimate framework of them all, being it for SEO or developer experience or performance. And since most of your, or even all of your HTML will be rendered at build time, the crawlers will be happy because they can index everything. So yeah, if you compare it to other frameworks, you can see Astro is right at the top there doing a very good stuff.

So if you're interested in taking Astro for a spin, you can just go to astro.new in your browser. You can set up a whole project in like two seconds on Stack Blitz, it goes very fast, all in the browser, really cool to play with. The Astro documentation is also amazing. We try to make it as accessible for everyone and as easy accessible for everyone. So it would be a great place for you to start if you want to read about it. If you don't feel like you can just go on docs, there is also full interactive tutorial on how you can build your own blog using Astro. We're also working on a new one specifically on the Astro islands architecture, really cool as well. And then of course I've put up some links here so I can get you started inside of the Astro space. You can check the tutorial there. There is also the astro.build.chat which is our Discord server. There is like a full support squad who will help you out if you have any questions and they will guide you on your astronomical journey through space. Cool, so yeah, this concludes my talk. Thanks for watching and I hope you find it interesting. And of course if you ever encounter any problems in Astro, feel free to ask. Yeah, this is my website and my Twitter handle so feel free to reach out to me. Thanks everyone and I hope to see you soon.