Skip to content

Thinking in views ​

A view is a rendering of the world that your page repeats whenever the world changes. Where to keep a value, when to update the screen and what to do after a click all follow from this model and from the few functions of the kit.

The world is the state ​

In most web apps the page fetches its data, keeps it, changes it and saves it back. A view works the other way round because the world owns the state (its data, the conversation with the person, the current state of its rules and who is in it). The world runs in UNaIVERSE and after every change the webapp passes your view a new snapshot of the part of the world that the person can see.

Your view has no data to fetch, no cache to refresh and no server to call for the world. Everything it reads is in one object, world:

FieldWhat it holds
name, profile, statusWho the world is and whether the person is in it.
dataWhat the world shows, by name: numbers, text, grids, pictures, files.
messagesThe conversation with the person from the oldest message to the newest.
nowThe current state of the rules, the states that can follow and the actions the person may choose.
canSendWhether the rules let the person send now.
members, roles, myRoleThe members, the roles and the role of the person.
webappThe theme and language of the webapp, the safe areas and keyboard of the screen and the browser features the person allowed.

Each change gives you a new and complete world object whose top-level fields are frozen. The arrays messages and members and the object data inside it are not frozen and must not be modified either.

Draw everything from the world ​

A view is a function from the world to the page. In plain JavaScript it is a function draw(node) that renders every part of the page from node. A React component plays the same role.

jsx
import { useWorld } from './useWorld.js';

// A fake world: a museum with a guide, and visitors that come and go.
const museum = {
	name: 'Museum',
	profile: { description: 'A small museum with a guide', place: 'Siena' },
	now: { text: 'The guide is in room 2' },
	data: { visitors: (time) => 20 + (Math.floor(time / 1000) % 7) },
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: museum } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	// Everything on the page comes from `world`, the world as it is now.
	return (
		<>
			<h2>{world.name}</h2>
			<p>{world.profile.description} · {world.profile.place}</p>
			<p>Now: {world.now?.text ?? 'nothing'}</p>
			<p>Visitors: {world.data.visitors}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world: a museum with a guide, and visitors that come and go.
const museum = {
	name: 'Museum',
	profile: { description: 'A small museum with a guide', place: 'Siena' },
	now: { text: 'The guide is in room 2' },
	data: { visitors: (time) => 20 + (Math.floor(time / 1000) % 7) },
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: museum } });

// The parts of the page, made once.
const title = document.createElement('h2');
const about = document.createElement('p');
const now = document.createElement('p');
const visitors = document.createElement('p');
document.body.append(title, about, now, visitors);

// Everything on the page comes from `node`, the world as it is now.
function draw(node) {
	title.textContent = node.name;
	about.textContent = `${node.profile.description} · ${node.profile.place}`;
	now.textContent = `Now: ${node.now?.text ?? 'nothing'}`;
	visitors.textContent = `Visitors: ${node.data.visitors}`;
}

// Draw at once, then after every change of the world.
world.subscribe(draw);
Live, on a fake world
Open

Although the number of visitors changes every second, no line of the code updates it. Each change of the world runs draw again and draw writes every line of the page. Rendering in this way has three consequences:

  • One place. Because every line of the page comes from draw, no part of the page can miss an update.
  • The first draw is not special. The page looks the same whether the world just arrived or changed for the hundredth time.
  • The fake world and the real one are drawn the same way. Nothing in draw knows which one it got.

Plain JavaScript: make the parts once, fill them in draw

Create your elements once outside draw and write only their text and attributes inside it. Rebuild a part (a list, a set of buttons) only when what it shows has changed. A form rebuilt on every change loses the text the person is typing and a button rebuilt ten times a second loses the keyboard focus.

One subscribe ​

world.subscribe(draw) calls draw at once with the current world and again after every change (a new value in data, a message, a new now or the webapp switching to the dark theme). Call it once when your page starts:

js
const world = await connectToHost();
world.subscribe(draw); // the first draw, and every one after it

The usual mistake is a subscribe inside an event handler that runs, for example, each time the person opens a panel. Every call adds a listener that stays until its stop function is called. After a few clicks each change of the world renders the page several times:

js
// Wrong: one more listener at every click.
openButton.onclick = () => {
  panel.hidden = false;
  world.subscribe((node) => drawPanel(node));
};

// Right: one subscribe draws everything; the click only changes what is yours.
let isPanelOpen = false;
openButton.onclick = () => {
  isPanelOpen = true;
  draw(world.get());
};
world.subscribe(draw); // draw() also draws the panel when isPanelOpen

subscribe returns a function that removes the listener. A part of the page that can be removed calls it when it goes away. A listener for the whole page usually never stops.

In React call useWorld once in your top component. Each call to useWorld opens its own connection to the webapp. When a second useWorld connects, the webapp ends the connection of the first one without an error and the first one receives no more updates. The other components receive the world as props from the top component (below).

Never copy values out of the world ​

A value copied out of the world is correct only until the next change. The example shows the same temperature twice (once from a copy taken at the start and once from the world) and the two lines diverge after the first second:

jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world whose temperature changes every second.
const station = {
	name: 'Weather station',
	data: { temperature: (time) => 18 + (Math.floor(time / 1000) % 10) },
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: station } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return <Temperatures world={world} />;
}

function Temperatures({ world }) {
	// Wrong: useState keeps the first value and ignores every change after it.
	const [copied] = useState(world.data.temperature);

	return (
		<>
			<p>Copied at the start: {copied} °C</p>
			{/* Right: read it from the world, at every render. */}
			<p>From the world: {world.data.temperature} °C</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world whose temperature changes every second.
const station = {
	name: 'Weather station',
	data: { temperature: (time) => 18 + (Math.floor(time / 1000) % 10) },
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: station } });

// Wrong: a copy, read once. It never changes again.
const copied = world.data.temperature;

const copyLine = document.createElement('p');
const liveLine = document.createElement('p');
document.body.append(copyLine, liveLine);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	copyLine.textContent = `Copied at the start: ${copied} °C`;
	// Right: read it from the world, every time.
	liveLine.textContent = `From the world: ${node.data.temperature} °C`;
});
Live, on a fake world
Open

The stale copy raises no error. The mistake comes in four forms:

  • A variable read once outside draw (const score = world.data.score;).
  • React state initialized from the world with useState(world.data.score) or with an effect that copies world into state. The state keeps its first value after the world has changed.
  • A list of messages of your own to which you push what the person sent. world.messages already holds those messages with their delivery status. A second list either shows them twice or misses the answers of the world.
  • The world you got at the start and read later. const world = await connectToHost() resolves with the world of that moment and a click handler that reads world.data still reads the data of that first world. world.get() returns the newest one:
js
button.onclick = () => {
  const node = world.get();          // the newest world
  if (node.data.round > 3) world.send('next');
};

Only the values go stale. The methods (send, act, onData, dataHistory, loadMore, get and the others) behave the same on every snapshot of the world including the first.

Act through the kit and let the world change ​

A click of the person does not change the screen directly. Your view asks the world with world.send(...), world.act(...) or message.answer(...) and the world decides what changes. A change of the world reaches the listener of subscribe and draw renders it.

In the example the button asks a counter world to add one. The page adds nothing itself and renders the new count when it arrives in the next snapshot of the world.

jsx
import { useWorld } from './useWorld.js';

// A fake world that keeps a count. Only the world changes it.
let count = 0;
const counter = {
	name: 'Counter',
	// The world shows its count, read again every 200 ms.
	data: { count: { every: 200, value: () => count } },
	// The world adds one when the person says 'add'. It answers nothing.
	onMessage: (message) => {
		if (message.text === 'add') count += 1;
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: counter } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			{/* The new count arrives with the next world. */}
			<p>Count: {world.data.count}</p>
			{/* Ask the world. The page does not add anything itself. */}
			<button onClick={() => world.send('add')}>Add one</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that keeps a count. Only the world changes it.
let count = 0;
const counter = {
	name: 'Counter',
	// The world shows its count, read again every 200 ms.
	data: { count: { every: 200, value: () => count } },
	// The world adds one when the person says 'add'. It answers nothing.
	onMessage: (message) => {
		if (message.text === 'add') count += 1;
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: counter } });

const shown = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Add one';
// Ask the world. The page does not add anything itself.
button.onclick = () => world.send('add');
document.body.append(shown, button);

// Called at once, then after every change of the world: the new count arrives here.
world.subscribe((node) => {
	shown.textContent = `Count: ${node.data.count}`;
});
Live, on a fake world
Open

Rendering count + 1 at once (an optimistic update) avoids the wait and is wrong for three reasons:

  • The world may refuse. send resolves to 'not-allowed' when it is not the turn of the person and 'failed' when the message is not delivered. In both cases the number added by the page is wrong.
  • The world may change more than the page expects. Only the world knows whether a move ends the game, changes the score of three players or gives the turn to someone else.
  • The kit already shows the message of the person at once in world.messages with status: 'sending' and then 'sent' or 'failed'. This immediate feedback needs no code of yours and reflects the real delivery.

The results of send and act ('sent', 'not-allowed', 'requested'...) tell the person what happened and never replace the world as the source of the page. Errors and the person's controls lists every result.

Derive what you show ​

Many values that a view shows are not fields of the world (whose turn it is, the last message of the world or how many moves the person made). Compute them from the world inside draw at every change instead of updating them by hand.

jsx
import { useWorld } from './useWorld.js';

// A fake duel: you are red. After your move, blue plays for one second.
let turn = 'red';
const duel = {
	name: 'Duel',
	myRole: 'red',
	roles: [{ name: 'red' }, { name: 'blue' }],
	data: { turn: { every: 200, value: () => turn } },
	onMessage: () => {
		turn = 'blue';
		setTimeout(() => { turn = 'red'; }, 1000);
		return 'Blue is thinking…';
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: duel } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	// Worked out from the world at every render, never stored.
	const isMyTurn = world.data.turn === world.myRole;
	const myMoves = world.messages.filter((message) => message.fromMe).length;
	const lastNews = world.messages.filter((message) => !message.fromMe).at(-1);

	return (
		<>
			<h2>{isMyTurn ? 'Your turn' : `Waiting for ${world.data.turn}`}</h2>
			<p>Moves you played: {myMoves}</p>
			<p>{lastNews ? lastNews.text : 'No news yet.'}</p>
			<button disabled={!isMyTurn || !world.canSend} onClick={() => world.send('move')}>
				Play a move
			</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake duel: you are red. After your move, blue plays for one second.
let turn = 'red';
const duel = {
	name: 'Duel',
	myRole: 'red',
	roles: [{ name: 'red' }, { name: 'blue' }],
	data: { turn: { every: 200, value: () => turn } },
	onMessage: () => {
		turn = 'blue';
		setTimeout(() => { turn = 'red'; }, 1000);
		return 'Blue is thinking…';
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: duel } });

const headline = document.createElement('h2');
const played = document.createElement('p');
const news = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Play a move';
button.onclick = () => world.send('move');
document.body.append(headline, played, news, button);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// Worked out from the world each time, never stored.
	const isMyTurn = node.data.turn === node.myRole;
	const myMoves = node.messages.filter((message) => message.fromMe).length;
	const lastNews = node.messages.filter((message) => !message.fromMe).at(-1);

	headline.textContent = isMyTurn ? 'Your turn' : `Waiting for ${node.data.turn}`;
	played.textContent = `Moves you played: ${myMoves}`;
	news.textContent = lastNews ? lastNews.text : 'No news yet.';
	button.disabled = !isMyTurn || !node.canSend;
});
Live, on a fake world
Open

Both versions compute isMyTurn, myMoves and lastNews from scratch at each change. Since no code has to toggle isMyTurn at the right moment, the value always matches the world. A few filters over a few hundred messages cost much less than rendering the page.

Views often derive these values:

WhatFrom the world
The last message of the worldnode.messages.filter((message) => !message.fromMe).at(-1)
Is it the person's turn?node.canSend or the data of the world (for example node.data.turn === node.myRole)
Who is online(node.members ?? []).filter((member) => member.status === 'online')
The person's failed messagesnode.messages.filter((message) => message.status === 'failed')
A ranking[...node.members].sort((a, b) => b.data.score - a.data.score)

Sort a copy

sort() and reverse() modify the array they are called on. To leave the world unchanged, sort a copy such as [...node.members].sort(...).

What is yours to keep ​

Not everything comes from the world. What only your page knows stays in a variable (plain JavaScript) or in state (React):

It belongs to the world: read it from worldIt is yours: keep it in your page
the data, the messages, the membersthe text the person is typing
the current state, whose turn it iswhether a panel or a menu is open
whether the person may send nowthe selected tab, the zoom, the scroll
the answer to a questionthe result of your last call (to explain it to the person)

A value that the world knows is read from the world. A value that only your page knows is kept by the page.

In React: one useWorld at the top, props down ​

In React the top component calls useWorld once and passes the world down as props. A component that only renders receives only the props it renders. Only a component with state of its own (the text being typed) keeps that state in useState.

jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world that answers every message.
const arena = {
	name: 'Arena',
	now: { text: 'Waiting for players' },
	onMessage: (message) => `Got it: ${message.text}`,
};

// The top component: the only one that calls useWorld.
export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<Header world={world} />
			<MessageList messages={world.messages} />
			<MessageBox world={world} />
		</>
	);
}

// Each part gets only what it draws.
function Header({ world }) {
	return <h2>{world.name}: {world.now?.text}</h2>;
}

function MessageList({ messages }) {
	if (messages.length === 0) return <p>No messages yet.</p>;
	return (
		<ul>
			{messages.map((message) => (
				<li key={message.id}>{message.fromMe ? 'You' : message.from}: {message.text}</li>
			))}
		</ul>
	);
}

function MessageBox({ world }) {
	// The words being written belong to the page, not to the world: keep them in state.
	const [text, setText] = useState('');

	function handleSubmit(event) {
		event.preventDefault();
		world.send(text);
		setText('');
	}

	return (
		<form onSubmit={handleSubmit}>
			<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Write a message" />
			<button disabled={!text || !world.canSend}>Send</button>
		</form>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that answers every message.
const arena = {
	name: 'Arena',
	now: { text: 'Waiting for players' },
	onMessage: (message) => `Got it: ${message.text}`,
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });

// Each part of the page: made once, drawn from the world.
const header = document.createElement('h2');
const list = document.createElement('ul');
const empty = document.createElement('p');
document.body.append(header, empty, list);

function drawHeader(node) {
	header.textContent = `${node.name}: ${node.now?.text ?? ''}`;
}

function drawMessages(node) {
	empty.textContent = node.messages.length === 0 ? 'No messages yet.' : '';
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		item.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text}`;
		return item;
	}));
}

// The message box. The words being written belong to the page, not to the world.
const form = document.createElement('form');
const input = document.createElement('input');
const send = document.createElement('button');
input.placeholder = 'Write a message';
send.textContent = 'Send';
form.append(input, send);
document.body.append(form);
form.onsubmit = (event) => {
	event.preventDefault();
	world.send(input.value);
	input.value = '';
	drawBox(world.get());
};
input.oninput = () => drawBox(world.get());

function drawBox(node) {
	send.disabled = !input.value || !node.canSend;
}

// One subscribe for the whole page: it draws every part.
world.subscribe((node) => {
	drawHeader(node);
	drawMessages(node);
	drawBox(node);
});
Live, on a fake world
Open
  • Header and MessageBox receive world. MessageList receives only messages and can be tested alone with a few sample messages.
  • MessageBox reads world.canSend from the world and keeps text in useState because the text belongs to the page and not to the world.
  • The plain JavaScript version has the same structure. One subscribe calls drawHeader, drawMessages and drawBox and the input element keeps the typed text.

For a deep component tree, put world in a React context at the top instead of passing it through every level. The context is filled by the one useWorld of the top component.

Putting it together ​

Every view, from a score on a screen to a full game, follows the same loop:

  1. The world is the state and your view does not own it.
  2. One draw renders everything from the world.
  3. One subscribe (in React one useWorld) runs draw at every change.
  4. Nothing is copied. What the page shows is derived from the current world.
  5. Act through the kit and render the world again when it changes.

Next steps ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.