useViewState function

Module @runic-artifex/react in @runic-artifex/react 0.23.0

function useViewState<TClient extends ViewClient, TSelected>(view: ViewHandle<TClient> | TClient | null | undefined, selector: (state: TClient["snapshot"]) => TSelected, isEqual?: (left: TSelected, right: TSelected) => boolean): TSelected | undefined;

Renders one selected part of a View's state and re-renders only when that part changes, by isEqual (Object.is by default), like useSyncExternalStoreWithSelector. Pass the connected client, which keeps its identity, to a memoized child, so the child renders when its member changes and not on every change of the View:

const Title = memo(function Title({ editor }: { editor: EditorClient | undefined }) {
  const title = useViewState(editor, state => state.title);
  return <h1>{title ?? "…"}</h1>;
});
const view = useView(page);
<Title editor={view.client} />

A useView handle works too, for example in the component that calls useView; that component still renders on every change of the handle. Returns undefined while there is no client and no state. The selector may be an inline function: a new function selects again, and an equal result keeps the previous value. Members the View did not change keep their identity, so selecting a member, or an object or array member, needs no isEqual; pass one for a derived value such as state => state.items.filter(…).