How to Use React with Astro: Simple Integration Guide
To use
React with Astro, install React packages and import React components inside your Astro files using client:load or other client directives. This lets Astro render React components on the client side while keeping the rest static.Syntax
In Astro, you import React components normally and add a client directive like client:load to tell Astro when to load the React component on the client side.
Example parts:
import MyComponent from './MyComponent.jsx'- imports React component<MyComponent client:load />- renders React component on client after page loads
astro
--- import MyComponent from './MyComponent.jsx' --- <html> <body> <MyComponent client:load /> </body> </html>
Example
This example shows a simple React button component used inside an Astro page. The button updates its label when clicked, demonstrating React's interactivity inside Astro.
astro
--- import React, { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ); } --- --- import Counter from './Counter.jsx' --- <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Astro React Example</title> </head> <body> <h1>React in Astro</h1> <Counter client:load /> </body> </html>
Output
<h1>React in Astro</h1>
<button>Clicked 0 times</button>
Common Pitfalls
Common mistakes when using React with Astro include:
- Forgetting to add a client directive like
client:load, so React components don’t hydrate and stay static. - Importing React components but not installing
reactandreact-dompackages. - Using server-only code inside React components that run on the client.
Always ensure React packages are installed and use client directives to enable interactivity.
astro
--- import Counter from './Counter.jsx' --- <html> <body> <!-- Wrong: no client directive, component won't hydrate --> <Counter /> <!-- Right: with client:load directive --> <Counter client:load /> </body> </html>
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Import React component | Bring React component into Astro file | import MyComp from './MyComp.jsx' |
| Client directive | Controls when React loads on client | |
| Other directives | Options like client:idle, client:visible | |
| Install packages | Add react and react-dom to project | npm install react react-dom |
Key Takeaways
Install react and react-dom packages before using React in Astro.
Import React components and add client directives like client:load to enable interactivity.
Without client directives, React components render static HTML only.
Use client:load to hydrate React components after page load for dynamic behavior.
Astro lets you mix React with static content for fast, interactive sites.