Skip to content

Switchable

The <Switchable> component shows one of several components, picked by a state value: the tabs of a settings screen, the panels of a dashboard, the steps of a wizard whose values should survive going back. Every component in of is created when the Switchable mounts and stays alive while hidden, so switching back shows it as it was.

It is not a router outlet: for the pages of an app, render only the current page, keyed by the route (Router). Hidden pages keep running (Pages with entry side effects), which an app’s pages rarely want.

import { xs, Switchable } from 'sygnal'
function HomePanel() {
return <p>Welcome home.</p>
}
function SettingsPanel() {
return <p>Your settings.</p>
}
function TabContainer({ state }) {
return (
<div>
<button className="tab-home">Home</button>
<button className="tab-settings">Settings</button>
<Switchable
of={{ home: HomePanel, settings: SettingsPanel }}
current={state.activeTab}
/>
</div>
)
}
TabContainer.initialState = { activeTab: 'home' }
TabContainer.intent = ({ DOM }) => ({
SET_TAB: xs.merge(
DOM.select('.tab-home').events('click').mapTo('home'),
DOM.select('.tab-settings').events('click').mapTo('settings')
)
})
TabContainer.model = {
SET_TAB: (state, data) => ({ ...state, activeTab: data })
}

When the Switchable’s state points at a different record (a changed path, or a byId() with a different id), Sygnal 7 disposes it and all its pages, hidden ones included, and mounts a new one. Switching the active page with the same state keeps the pages alive, as described below. A Switchable bound with a custom lens keeps its pages until its key changes. See state lifetimes.

PropTypeDescription
ofObjectMaps names to components: { name: Component }
currentStringThe name of the currently active component
instanceString or NumberOptional key of the current page’s instance: when it changes, the page is created again with fresh state (below)
stateString, Lens, or an object of them per pageOptional state slice for the switched components, or one per page (below)

Give each page its own slice with a map from page names to bindings. Each entry is what a tag child’s state can be: a key, a path, a lens or a byId() selection. The pages not in the map share the owner’s state:

<Switchable
of={{ projects: Projects, settings: Settings, help: Help }}
current={state.page}
state={{ projects: 'pages.projects', settings: byId('teams', state.teamId) }}
/>
  • Each page follows its own binding with a tag child’s lifetime rules: when an entry points at another record (another key, another id), only that page is disposed and made again; the others keep their instances. When its record is deleted, the page is disposed with its last state (its DISPOSE sees it; nothing is written back), and a new one renders once the record is there again.
  • Every page still starts at mount and keeps working while hidden, on its own slice: its BOOTSTRAP runs at mount too (Pages with entry side effects).
  • A map key that is not one of the of pages binds nothing, so the page it was meant for shares the owner’s state: the dev checks and sygnal-check report it as SYG429.
  • A routed page needs no copy of the route in its slice: provide route as context and read it in the page’s view and statics.
  • Only the current component’s DOM is rendered
  • Non-DOM sinks (EVENTS, PARENT, driver sinks) from all components remain active; a component’s PARENT reaches the parent’s CHILD.select(Component)
  • Switching is efficient: every component is instantiated up front and stays alive while hidden, so memory grows with the number of pages (and what they hold), not with switching
  • A hidden component keeps its own state and sub-components, and keeps working on the current state: its reducers, EVENTS/PARENT/EFFECT answers and .context see the state changed while it was hidden. Only its rendering waits: it doesn’t re-render while hidden, and renders the current state once when switched back in (until then the previous page stays on screen, never the hidden page’s old content)
  • A hidden component’s connections and resources pause, except the entries marked background: true (below)
  • current must be one of the keys of of (SYG416), and of must map names to component functions (SYG415)
  • When the Switchable itself is removed, all of its components are disposed, including any nested Collections

Pages stay alive across switches, so a page shown for one record keeps its state when the app shows it for another (a draft typed for task 1 would still be there for task 2). Give the Switchable an instance key: when it changes, the current page is disposed (its DISPOSE action runs, its connections close, its requests are aborted) and created again with fresh state.

import { Switchable } from 'sygnal'
function App({ state }) {
return (
<main>
<Switchable
of={{ list: TaskList, task: TaskPage }}
current={state.page}
instance={state.taskId}
/>
</main>
)
}
App.initialState = { page: 'list', taskId: null }
  • Switching current without changing instance keeps the pages alive, as before.
  • A hidden page is re-created when it’s shown again with another key than the one it last had (it was hidden while the key changed). A page that was never shown takes the key it’s first shown with.
  • instance suits a panel shown for one record at a time (a task id, a step number). For routed pages use a keyed page instead of a Switchable (Router).
  • The page sees the new state once before it is re-created (state reaches it before the Switchable re-renders with the new key), so in that moment it may start a request or open a connection for the new values; disposing the old instance aborts or closes it right away.

Every page in of is created when the Switchable mounts, whether or not it is the current page, and keeps running while hidden:

  • its BOOTSTRAP runs at mount;
  • its intent is subscribed, so its STATE.watch() streams fire on state changes made while another page shows;
  • its model sinks (EFFECT, HTTP, ROUTER, …) run for those actions: a hidden page can send a request;
  • its resources are declared under their names, so two pages that declare the same resource name collide (only the requests pause while hidden, below).

That suits pages whose start and updates are harmless (a tab that loads its data, which pauses while hidden). It doesn’t suit pages whose start or watches do something: a logout page whose BOOTSTRAP signs the user out, a page that saves when a value changes, a wizard that redirects on entry. Mount them all and the logout runs on page load.

For those, give the Switchable only the current page, and key it by the page so that another page makes a new Switchable:

App.jsx
import { Switchable } from 'sygnal'
const PAGES = { projects: Projects, wizard: Wizard, logout: Logout }
const PAGE_STATE = { projects: 'pages.projects', wizard: 'pages.wizard' }
function App({ state }) {
const page = state.route.name
return (
<main>
<Switchable
key={page}
of={{ [page]: PAGES[page] }}
current={page}
state={PAGE_STATE[page] ? { [page]: PAGE_STATE[page] } : undefined}
instance={state.route.path}
/>
</main>
)
}
App.initialState = { route: { name: 'projects', path: '/' }, pages: { projects: {}, wizard: {} } }
  • Only the shown page exists, so a page’s BOOTSTRAP runs when it is first shown, every time it is shown.
  • Going back to a page creates it again: what it keeps in its own slice of the owner’s state (pages.projects here) is still there, its resources refetch (from the cache, if the fetch driver has one), and its local state starts over.
  • For a router this is the keyed page without the Switchable: <Page key={`${route.name}:${route.path}`} />.

This changes page lifetimes compared with a Switchable over every page, so moving lens-hosted pages to one Switchable with a per-page state map needs this pattern for any page with entry side effects.

A Switchable doesn’t scroll: it only shows another page. With makeRouter, navigation does: a new page (a link or a push) scrolls to the top, or to the #hash target, and back/forward restores where the user was. A Switchable driven by state alone, such as tabs or the steps of a wizard, stays where it is, which is what tabs want. When a step change should scroll, send an element command from the action that changes the step: NEXT_STEP: { STATE: …, ELEMENT: { scrollIntoView: '.wizard', block: 'start' } }.

Hidden pages pause connections and resources

Section titled “Hidden pages pause connections and resources”

While a page is hidden, it and every component inside it (sub-components and Collection items) declare only the connections and resources entries marked background: true. The others pause: their sockets close (without a close action), and their resource requests in flight are aborted while each resource keeps its last result (or goes back to idle if nothing had arrived). When the page is shown again, every entry is declared again: the sockets open as new connections (open with reconnected: false) and the resources refetch, keeping their data with refreshing: true (Resources and Caching).

function Chat({ state }) {
return <ul>{state.messages.map((m) => <li>{m.text}</li>)}</ul>
}
Chat.initialState = { roomId: 'general', messages: [], unread: 0 }
Chat.connections = (state) => ({
// closes while the page is hidden
room: { socket: `/ws/rooms/${state.roomId}`, message: 'RECEIVED' },
// stays open: counts notifications for the badge in the header
alerts: { socket: '/ws/alerts', message: 'ALERT', background: true },
})
Chat.model = {
RECEIVED: (state, msg) => ({ ...state, messages: [...state.messages, msg] }),
ALERT: (state) => ({ ...state, unread: state.unread + 1 }),
}
  • background goes on the entry ({ socket, background: true }, { url, background: true }), not on the component.
  • Messages a paused socket would have received are not replayed: mark a connection background: true when the page must not miss them while hidden.
  • A declaration that isn’t a set of entries (the router’s route) stays live while hidden.

The lowercase <switchable> and <collection> tags, which work without an import, are deprecated since 6.3.0 and will be removed in the next major (they will then render unknown elements). To migrate, add import { Switchable } from 'sygnal' (or Collection) and write <Switchable …>; sygnal-check --fix makes both changes, and the dev diagnostics report the lowercase tags as SYG426.