Here’s a self-contained HTML file that demonstrates Zustand with Preact in a simple counter app. You can paste this into any HTML playground (like CodePen, JSFiddle, or a local .html file):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zustand + Preact Counter</title>
<script src="https://unpkg.com/preact@10.19.2/dist/preact.umd.js"></script>
<script src="https://unpkg.com/zustand@4.4.5/dist/zustand.umd.js"></script>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
button { padding: 8px 16px; font-size: 16px; cursor: pointer; }
</style>
</head>
<body>
<div id="app"></div>
<script>
const { h, render } = window.preact;
const { create: createStore } = window.zustand;
// 1. Create a Zustand store
const useStore = createStore((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
// 2. Preact Component using Zustand
function Counter() {
const { count, increment, decrement } = useStore();
return h('div', null,
h('h1', null, 'Counter: ', count),
h('button', { onClick: decrement }, 'Decrement'),
h('button', { onClick: increment }, 'Increment')
);
}
// 3. Render the app
render(h(Counter), document.getElementById('app'));
</script>
</body>
</html>
How It Works:
- Preact and Zustand UMD builds are loaded from CDN (no build step needed).
- A Zustand store is created with
count, increment, and decrement.
- A Preact component uses the store via
useStore() hook.
- The app is rendered into the
#app div.
Try It:
- Copy/paste this into an HTML file and open it in a browser.
- Or use an online playground like CodePen (just paste the
<script> and <style> parts).
Output:
You’ll see a counter with two buttons to increment/decrement the value. Zustand manages the state, and Preact handles the UI updates efficiently.
Let me know if you'd like to extend this (e.g., add middleware, persistence, or async actions)!