Certainly! Below is a self-contained HTML file that includes everything needed to run a Preact application with Zustand. You can copy this code into an HTML file and open it in your browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preact with Zustand</title>
<script crossorigin src="https://unpkg.com/react/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/preact/dist/preact.module.js"></script>
<script crossorigin src="https://unpkg.com/zustand"></script>
</head>
<body>
<div id="app"></div>
<script type="module">
import { h, render } from 'https://unpkg.com/preact';
import create from 'https://unpkg.com/zustand';
// Create a store using Zustand
const useStore = create((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
}));
// Define a Preact component
const Counter = () => {
const { count, increase, decrease } = useStore();
return (
h('div', null,
h('h1', null, 'Count: ', count),
h('button', { onClick: increase }, 'Increase'),
h('button', { onClick: decrease }, 'Decrease')
)
);
};
// Render the Preact component
render(h(Counter), document.getElementById('app'));
</script>
</body>
</html>
Explanation:
-
Scripts:
- React and React DOM are included for compatibility, though Preact will be used for rendering.
- Preact and Zustand are loaded from a CDN.
-
Module Script:
- The module script imports
h and render from Preact and create from Zustand.
- A Zustand store is created to manage the count state.
- A Preact component
Counter is defined to display and modify the count.
- The
Counter component is rendered inside the div with the ID app.
You can copy this code into an HTML file and open it in your browser to see the Preact application with Zustand in action.