create Graft

Turn a hook into a provider and a matching `use()` hook.

Usage

The hook owns the state and its actions. createGraft makes them available to the components below the provider.

tsx
// react-graft-create-graft-likes.graft.ts
export const ReactGraftCreateGraftLikesGraft = createGraft({
  name: "ReactGraftCreateGraftLikesGraft",
  graft: useGraft,
});

function useGraft({ start = 0 }: { start?: number }) {
  const [value, setValue] = useState(start);

  const like = useCallback(() => setValue((count) => count + 1), []);
  const reset = useCallback(() => setValue(start), [start]);

  return { value, like, reset };
}

The hook's options become the provider's props. Any component below it can read the return value with use().

tsx
// react-graft-create-graft-likes-panel.tsx
export const ReactGraftCreateGraftLikesPanel = () => (
  <ReactGraftCreateGraftLikesGraft.Provider start={10}>
    <ReactGraftCreateGraftLikeButton />
  </ReactGraftCreateGraftLikesGraft.Provider>
);

// react-graft-create-graft-like-button.tsx
export const ReactGraftCreateGraftLikeButton = () => {
  const { like, value } = ReactGraftCreateGraftLikesGraft.use();

  return (
    <Button onClick={like}>
      <Button.Label>{`likes: ${value}`}</Button.Label>
    </Button>
  );
};

inject

Put feature-wide rules in inject so they run wherever the graft is used. Here, reaching 5 likes asks whether to start over, whichever instance reached the limit.

tsx
// react-graft-create-graft-likes-limit.graft.ts
export const ReactGraftCreateGraftLikesLimitGraft = createGraft({ name: "ReactGraftCreateGraftLikesLimitGraft", graft: useConfirm });

// react-graft-create-graft-likes.graft.ts
export const ReactGraftCreateGraftLikesGraft = createGraft({
  name: "ReactGraftCreateGraftLikesGraft",
  graft: useGraft,
  inject: [useInjectLimit],
});

function useInjectLimit({ reset, value }: { reset: () => void; value: number }) {
  const { open } = ReactGraftCreateGraftLikesLimitGraft.use();

  useEffect(() => {
    if (value < LIKE_LIMIT) return;

    let cancelled = false;

    void open().then((confirmed) => {
      if (cancelled || !confirmed) return;

      reset();
    });

    return () => {
      cancelled = true;
    };
  }, [open, reset, value]);
}

// react-graft-create-graft-likes-demo.tsx
export const ReactGraftCreateGraftLikesDemo = ({ start }: { start: number }) => (
  <ReactGraftCreateGraftLikesLimitGraft.Provider>
    <ReactGraftCreateGraftLikesGraft.Provider start={start}>
      <ReactGraftCreateGraftLikeButton />
      <ReactGraftCreateGraftLimitLayer />
    </ReactGraftCreateGraftLikesGraft.Provider>
  </ReactGraftCreateGraftLikesLimitGraft.Provider>
);

Side effects

Syncing the URL, saving, listening for a shortcut: effects like these go in inject too, so no component has to remember to call them.

tsx
// react-graft-invoice-editor-dialog.graft.ts
export const ReactGraftInvoiceEditorDialogGraft = createGraft({
  name: "ReactGraftInvoiceEditorDialogGraft",
  graft: useGraft,
  inject: [useInjectUrl],
});

function useInjectUrl({ isActive, storage }: { isActive: boolean; storage: Invoice | null }) {
  const { invoice } = useSearch({ strict: false });
  const navigate = useNavigate();

  useEffect(() => {
    const target = isActive ? storage?.id : undefined;
    if (invoice === target) return;

    void navigate({ to: "/invoices", search: { invoice: target }, replace: true });
  }, [invoice, isActive, navigate, storage?.id]);
}

Extending another hook

The hook can build on another one and replace part of what it returns. Here close asks for confirmation first.

tsx
// react-graft-invoice-editor-dialog.graft.ts
export const ReactGraftInvoiceEditorDialogGraft = createGraft({ name: "ReactGraftInvoiceEditorDialogGraft", graft: useGraft });

function useGraft() {
  const dialog = useDialog<Invoice>();
  const discard = ReactGraftInvoiceEditorAlertDiscardGraft.use();

  const close = useCallback(async () => {
    if (!(await discard.open())) return;

    dialog.close();
  }, [dialog, discard]);

  return { ...dialog, close };
}

Reference

Options

proptypedefault
graft(options) => TValue—the hook the provider mounts
inject?((value: TValue) => void)[][]extra hooks run inside the provider, with the value as argument
name?string"Graft"shown in React DevTools and in the error

Returns

proptypedefault
Provider(props: TOptions) => ReactNode—runs the hook with its options as props
use() => TValue—reads the hook's return value; throws outside the provider
displayNamestring—the name it was given