React Graft

Turns a hook into a context: write the state once, read it anywhere below its provider.

Usage

Put your state and actions in a hook, pass it to createGraft, then wrap the components that need it in the provider. They can all read the value with use().

tsx
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), []);

  return { value, like };
}

<ReactGraftCreateGraftLikesGraft.Provider start={10}>
  <ReactGraftCreateGraftLikeButton />
</ReactGraftCreateGraftLikesGraft.Provider>

const { value, like } = ReactGraftCreateGraftLikesGraft.use();

What you get

  • One typed contract. The hook's options become the provider's props, and its return value is what use() gives you. Define the shape once.
  • A private context. You never export the context itself. If use() runs outside its provider, it throws an error that names the graft.
  • A home for shared effects. inject runs extra hooks inside the provider, for things like keeping the URL in sync or saving to storage.

Limits

A graft is plain React: a hook, a provider, and a context. It has no proxies or selectors, so every component that reads the value re-renders when that value changes.