Files
sweet/docs/latest/examples/sharing-state-between-islands.md
T
Christian Svensson a2de5154ec fix(docs): improve and increase consistency for code blocks (#3163)
Follow-up from #3162.

This PR does various tweaks, mostly related to code blocks.

- Adds missing titles to code blocks, and updates titles to be more
consistent
- Adds filenames to most ` ```tsx` blocks with e.g. `main.ts`, `dev.ts`
or a suitable example (e.g. `routes/greeting.tsx`) based on the code
- Adds filenames to ` ```diff` blocks if there's a relevant file, to
make the icon e.g. TS over Diff icon
  - Code blocks with Fresh code (e.g. interfaces) uses ` ```tsx fresh 🍋`
- Changes most ` ```sh` blocks with example terminal commands to ` ```sh
Terminal`
- Updates ` ```txt Project Structure` or ` ```diff Project Structure`
blocks to be more consistent
- Changes `sh` or `txt` to `txt-files` which improves highlighting and
makes icon consistent
- Renames `<project dir>` to `<project root>` to match builder `root`
option terminology
- Adds `<project root>` root folder to most/all overview folder
overviews
  - Makes the structure blocks more consistently displayed
- Tried to make some "bare" examples more complete

## Comparison

Here's a small curated set of before/after changes.

### Deployment

- `deno` highlighted in terminal commands
- `.gitignore` syntax highlighting works without using `sh` as language

<img width="1641" height="1009" alt="image"
src="https://github.com/user-attachments/assets/170cf833-1f6a-4b0d-8d2d-a081bc28a967"
/>

### File routing

Updated icon, comments same as before, but root and hierarchy have new
colors (`operator`/`function`).

<img width="1647" height="588" alt="image"
src="https://github.com/user-attachments/assets/f28db51b-4bee-45e4-be1c-e137a6d3ae3d"
/>
2025-08-01 09:07:42 +02:00

190 lines
4.7 KiB
Markdown

---
description: |
When you need to have state shared between islands, this page provides a few recipes.
---
All of this content is lifted from this great
[example](https://fresh-with-signals.deno.dev/) by Luca. The source can be found
[here](https://github.com/lucacasonato/fresh-with-signals).
## Multiple Sibling Islands with Independent State
Imagine we have `Counter.tsx` like this:
```tsx islands/Counter.tsx
import { useSignal } from "@preact/signals";
import { Button } from "../components/Button.tsx";
interface CounterProps {
start: number;
}
// This island is used to display a counter and increment/decrement it. The
// state for the counter is stored locally in this island.
export default function Counter(props: CounterProps) {
const count = useSignal(props.start);
return (
<div class="flex gap-2 items-center w-full">
<p class="flex-grow-1 font-bold text-xl">{count}</p>
<Button onClick={() => count.value--}>-1</Button>
<Button onClick={() => count.value++}>+1</Button>
</div>
);
}
```
Note how `useSignal` is within the `Counter` component. Then if we instantiate
some counters like this...
```tsx routes/index.tsx
<Counter start={3} />
<Counter start={4} />
```
they'll keep track of their own independent state. Not much sharing going on
here, yet.
## Multiple Sibling Islands with Shared State
But we can switch things up by looking at a `SynchronizedSlider.tsx` like this:
```tsx islands/SynchronizedSlider.tsx
import { Signal } from "@preact/signals";
interface SliderProps {
slider: Signal<number>;
}
// This island displays a slider with a value equal to the `slider` signal's
// value. When the slider is moved, the `slider` signal is updated.
export default function SynchronizedSlider(props: SliderProps) {
return (
<input
class="w-full"
type="range"
min={1}
max={100}
value={props.slider.value}
onInput={(e) => (props.slider.value = Number(e.currentTarget.value))}
/>
);
}
```
Now if we were to do the following...
```tsx routes/index.tsx
export default function Home() {
const sliderSignal = useSignal(50);
return (
<div>
<SynchronizedSlider slider={sliderSignal} />
<SynchronizedSlider slider={sliderSignal} />
<SynchronizedSlider slider={sliderSignal} />
</div>
);
}
```
they would all use the same value.
## Independent Islands
We can also create a `signal` in a utility file and export it for consumption
across multiple places.
```ts utils/cart.ts
import { signal } from "@preact/signals";
export const cart = signal<string[]>([]);
```
```tsx islands/AddToCart.tsx
import { Button } from "../components/Button.tsx";
import { cart } from "../utils/cart.ts";
interface AddToCartProps {
product: string;
}
// This island is used to add a product to the cart state.
export default function AddToCart(props: AddToCartProps) {
return (
<Button
onClick={() => (cart.value = [...cart.value, props.product])}
class="w-full"
>
Add{cart.value.includes(props.product) ? " another" : ""} "{props.product}
" to cart
</Button>
);
}
```
```tsx islands/Cart.tsx
import { Button } from "../components/Button.tsx";
import { cart } from "../utils/cart.ts";
import * as icons from "../components/Icons.tsx";
// This island is used to display the cart contents and remove items from it.
export default function Cart() {
return (
<h1 class="text-xl flex items-center justify-center">
Cart
</h1>
<ul class="w-full bg-gray-50 mt-2 p-2 rounded-sm min-h-[6.5rem]">
{cart.value.length === 0 && (
<li class="text-center my-4">
<div class="text-gray-400">
<icons.Cart class="w-8 h-8 inline-block" />
<div>
Your cart is empty.
</div>
</div>
</li>
)}
{cart.value.map((product, index) => (
<CartItem product={product} index={index} />
))}
</ul>
);
}
interface CartItemProps {
product: string;
index: number;
}
function CartItem(props: CartItemProps) {
const remove = () => {
const newCart = [...cart.value];
newCart.splice(props.index, 1);
cart.value = newCart;
};
return (
<li class="flex items-center justify-between gap-1">
<icons.Lemon class="text-gray-500" />
<div class="flex-1">
{props.product}
</div>
<Button onClick={remove} aria-label="Remove" class="border-none">
<icons.X class="inline-block w-4 h-4" />
</Button>
</li>
);
}
```
Now we can add the islands to our site by doing the following:
```tsx routes/cart.tsx
<AddToCart product="Lemon" />
<AddToCart product="Lime" />
<Cart />
```
What happens as a result? The `cart` signal is shared across the two `AddToCart`
islands _and_ the `Cart` island.