State Persistence
The 7 controlled-state props (selection, viewState, is3D, theme,
hoveredId, pinned, hidden) let you round-trip canvas state through
any external store — React state, Redux, URL search params, IndexedDB,
the server. This page shows three common patterns.
Pattern 1 — URL params (shareable links)
Encode the view into the URL so users can paste a link and reproduce the exact selection + camera state.
import { useState, useEffect } from "react";
import { GraphCanvas, type SelectionState, type ViewState } from "@kineviz/gl";
function decodeFromURL() {
const p = new URLSearchParams(window.location.search);
return {
selection: p.get("sel")
? { nodes: p.get("sel")!.split(","), edges: [] } as SelectionState
: undefined,
viewState: p.get("vs") ? JSON.parse(atob(p.get("vs")!)) as ViewState : undefined,
};
}
function encodeToURL(sel: SelectionState, vs: ViewState) {
const p = new URLSearchParams(window.location.search);
if (sel.nodes.length > 0) p.set("sel", sel.nodes.join(","));
else p.delete("sel");
p.set("vs", btoa(JSON.stringify(vs)));
window.history.replaceState(null, "", `?${p}`);
}
export function ShareableGraph() {
const initial = decodeFromURL();
const [selection, setSelection] = useState<SelectionState>(
initial.selection ?? { nodes: [], edges: [] }
);
const [viewState, setViewState] = useState<ViewState | undefined>(initial.viewState);
useEffect(() => {
if (viewState) encodeToURL(selection, viewState);
}, [selection, viewState]);
return (
<GraphCanvas
data={myGraph}
selection={selection}
onSelectionChange={setSelection}
viewState={viewState}
onViewStateChange={setViewState}
forceLayout
/>
);
}
Key points:
- Initial render reads URL → seeds state → engine snaps to that view.
- User interaction → engine fires
onSelectionChange/onViewStateChange→ state updates → URL re-encoded. - Paste a URL → page loads → state seeds → engine snaps. Round-trip.
viewStateis base64-encoded because raw{"position":[1,2,3],...}JSON is awkward in URLs. Encode whatever subset makes sense for your app.
Pattern 2 — Redux / Zustand store
When canvas state lives alongside other app state, mirror it into your store and use selector hooks to feed back into the prop:
// store.ts
import { create } from "zustand";
interface AppState {
selection: SelectionState;
setSelection: (s: SelectionState) => void;
viewState: ViewState | undefined;
setViewState: (v: ViewState) => void;
}
export const useApp = create<AppState>((set) => ({
selection: { nodes: [], edges: [] },
setSelection: (selection) => set({ selection }),
viewState: undefined,
setViewState: (viewState) => set({ viewState }),
}));
// Graph.tsx
export function Graph() {
const selection = useApp((s) => s.selection);
const setSelection = useApp((s) => s.setSelection);
const viewState = useApp((s) => s.viewState);
const setViewState = useApp((s) => s.setViewState);
return (
<GraphCanvas
data={myGraph}
selection={selection}
onSelectionChange={setSelection}
viewState={viewState}
onViewStateChange={setViewState}
forceLayout
/>
);
}
// SideBar.tsx — read & set the same state from elsewhere
function SidePanel() {
const { selection, setSelection } = useApp();
return (
<button onClick={() => setSelection({ nodes: ["n1", "n2"], edges: [] })}>
Select two nodes from outside the canvas
</button>
);
}
Programmatic writes from anywhere in the app (panel buttons, command
palette, undo system) just call setSelection, the prop changes, the
engine snaps. No apiRef plumbing.
Pattern 3 — localStorage (per-user view memory)
Remember the last view between sessions:
const KEY = "graph-view";
function loadSavedView() {
try { return JSON.parse(localStorage.getItem(KEY) ?? "{}"); }
catch { return {}; }
}
function saveView(view: { selection: SelectionState; viewState: ViewState }) {
localStorage.setItem(KEY, JSON.stringify(view));
}
export function PersistentGraph() {
const saved = loadSavedView();
const [selection, setSelection] = useState<SelectionState>(
saved.selection ?? { nodes: [], edges: [] }
);
const [viewState, setViewState] = useState<ViewState | undefined>(saved.viewState);
// Debounce save (throttle to once per second to avoid disk churn).
useEffect(() => {
if (!viewState) return;
const t = setTimeout(() => saveView({ selection, viewState }), 1000);
return () => clearTimeout(t);
}, [selection, viewState]);
return (
<GraphCanvas
data={myGraph}
selection={selection}
onSelectionChange={setSelection}
viewState={viewState}
onViewStateChange={setViewState}
forceLayout
/>
);
}
Controlled vs uncontrolled
| Mode | When to use | Example |
|---|---|---|
Controlled (selection={...} + onSelectionChange) |
Host owns truth; you want to persist / share / programmatically set | The 3 patterns above |
Uncontrolled (defaultSelection={...} only) |
Initial value matters but you don't need ongoing sync | Storybook stories, screenshots, simple demos |
| Neither (omit both) | Engine manages internally | The default — host doesn't care about selection state |
Mixing modes (passing both selection AND defaultSelection) fires a
one-shot dev warning and silently picks the controlled value. Don't mix.
Per-state notes
viewState— engine has noview:positionChangedevent; the hook RAF-polls only whenonViewStateChangeis registered. Zero overhead when you omit the callback.hoveredId— 2-piece (nodefaultHoveredId). Programmatic hover doesn't fire the hover-emphasis dim effect (that's reserved for real pointer events).pinned/hidden— edge-targeted entries (edges: [...]) are forward-compat fields the engine currently ignores; safe to include.is3D/theme— booleans / preset strings. Simplest pairs.
See also
GraphCanvasProps— all 7 controlled pair declarationsapi.history— undo/redo system (orthogonal to controlled state)