usePuck
A hook for accessing the PuckApi
as part of your React render lifecycle.. The best way to access usePuck
is via the createUsePuck()
factory.
import { createUsePuck } from "@measured/puck";
const usePuck = createUsePuck();
const Example = () => {
const type = usePuck((s) => s.selectedItem?.type || "Nothing");
return <h2>{type} selected</h2>;
};
You can also access usePuck
as a direct export, but you won’t be able to use selectors, resulting in unwanted re-renders and degraded performance.
Args
Param | Example | Type |
---|---|---|
selector(data) | (s: PuckApi) => s.appState | Function |
selector(data)
A selector function that describes what usePuck
returns. Receives PuckApi
and returns anything. Be as granular as possible to minimize re-renders.
// Good: only re-render when the `selectedItem` changes
const selectedItem = usePuck((s) => s.selectedItem);
// Bad: re-render when anything changes
const { selectedItem } = usePuck();
const { selectedItem } = usePuck((s) => s);
// Bad: selector creates a new object reference, causing an infinite comparison loop
const { selectedItem } = usePuck((s) => ({ ...s.selectedItem }));
Returns
Whatever is returned by the selector
.