Skip to content
These are temporary community docs. The official docs are in progress.Help improve them
Markless
Esc
↑↓navigate↵open⌘Jpreview
On this page

Shared state

Share one piece of state between components with shared().

A computed lives inside one component. Now a badge and a button, in two components, both need the same count.

Define the state once with shared(). Each component that calls the definition gets the same count. A change from one component shows up in the other.

Click +1 in the figure.

Can a click in one component change another?

Press +1 in Counter. Watch the number in Badge.

The pageTry it
Counter
Counter
Badge0
Your code: Counter.tsrx
import { shared, state } from '@markless/core'; export const counter = shared(() => { const box = state({ count: 0 }); return { ...box, increment() { box.count++; } };}, { scope: 'page' }); function Badge() @{ const c = counter(); (same count) <output>{c.count}</output>} export default function Counter() @{ const c = counter(); (same count) <main><Badge /><button onClick={() => c.increment()}>+1</button></main>}
What Markless did
Copies of count1Both components share it
Texts updated in Badge0Each click changes one
  1. noteBadge and Counter both call counter(). They get one shared count.

Simplified. The dashed boxes show which component made each part of the page. They are not on the real page.

Notice that the click runs in Counter, but the number changes in Badge.

import { shared, state } from '@markless/core';

export const counter = shared(() => {
	const box = state({ count: 0 });
	return { ...box, increment() { box.count++; } };
}, { scope: 'page' });

function Badge() @{
	const c = counter();
	<output>{c.count}</output>
}

export default function Counter() @{
	const c = counter();
	<main><Badge /><button onClick={() => c.increment()}>+1</button></main>
}

The function inside shared() creates the state. It returns the state plus any methods, like increment().

Who shares it

The second argument picks the group that shares one copy.

Scope Who gets the same copy
{ scope: 'page' } Every component on the page. This is the default.
{ scope: 'widget' } One copy for each rendered widget, like each menu or each dialog.

UI components use 'widget' so each menu keeps its own open or closed state.

Use state() when one component owns the value. Use shared() when several components need it.

Next: How does a click reach increment()? Events →

Was this page helpful?