useCanvasState

Persists the canvas camera (x, y, scale) and the currently peeked folder to localStorage, so a canvas returns to where the user left it. Pass the restored camera to <Canvas> as its initial state and feed onCameraSettle back into the setter.

Installation

npx shadcn@latest add https://canvas.blode.co/r/use-canvas-state.json

Usage

const { camera, setCameraState } = useCanvasState("my-canvas");
 
return (
  <Canvas
    initialScale={camera.scale}
    initialX={camera.x}
    initialY={camera.y}
    onCameraSettle={setCameraState}
  >
    {children}
  </Canvas>
);

Because the restore runs after first paint, gate the <Canvas> behind a mount flag (or restored) so its initial camera reflects the saved view.

API

PropTypeDefaultDescription
storageKeystring"canvas-view"Argument, the localStorage key to read/write.
camera{ x; y; scale }The restored (or default) camera state.
peekedFolderstring | nullId of the folder that was peeked open.
restoredbooleanTrue once a saved state has been loaded.
setCameraState(camera) => voidPersist a new camera (no-op if unchanged).
setPeekedFolder(id | null) => voidPersist the peeked folder id.