Hooks, made shareable

Bring your hook into the tree

Turn a hook into a typed context. Its state, logic and feature effects live together in a provider, ready for any component beneath it.

const useCart = ({ currency }: { currency: string }) => {
  const [items, setItems] = useState<string[]>([]);
  const add = (item: string) => setItems((list) => [...list, item]);

  return { currency, items, add };
};

export const GraftCart = createGraft({ name: "GraftCart", graft: useCart });

<GraftCart.Provider currency="EUR">
  <Checkout />
</GraftCart.Provider>;

const { items, add } = GraftCart.use();

get started

npm install react-graft

under 1 kB minified and gzipped

The idea

A hook, a provider, a use(). Put a feature's state, actions and effects in a hook, pass it to createGraft, then wrap the components that need it. They can all read the same feature through use().

More than a store

A graft is more than a place to keep values. It brings a feature's state, the logic that changes it and the effects that follow it into one hook, shared with every component below its provider.

In the tree, not global

A graft lives in the branch where its provider is mounted. The UI decides when it starts and when it ends: it mounts with the provider and unmounts with it, state and effects included. Nothing to reset, nothing to clean up by hand.

Inside the rules of React

No proxies, no selectors, no subscriptions: a hook, a provider and a context. Every component that reads a graft re-renders when its value changes, as with any context.

createGraft

Give a hook a home in your tree

createGraft turns your hook into a feature-sized context: a Provider runs it, and use lets components beneath the provider read its return value. Only graft is required; name and inject have defaults.

graft

type (options: TOptions) => TValuerequired

The hook the provider runs. Pass the hook itself, useCart, not its result: the provider calls it on every render, so it follows the rules of hooks like any other.

It takes one argument, an options object, and returns the value you want to share. The options become the provider's props: currency here is both what the hook reads and what GraftCart.Provider asks for, typed from the hook's signature. Leave out a required option and TypeScript tells you on the provider.

What it returns is what every use() below gets: state, actions, derived values, anything. A hook you already have works as it is, including one from react-graft/hooks with its type argument, or a useQuery.

name

type stringdefault "Graft"

The name of the graft. React DevTools shows the context as GraftCart and the provider as GraftCart.Provider, so a tree with many grafts stays readable.

It also goes in the error that use() throws outside its provider: GraftCart was read outside its provider. Without a name both say Graft, which tells you little once there are several.

Give it the same name as the constant it's assigned to.

inject

type GraftInject<TValue>[]default []

Hooks that run inside the provider, for the effects that belong to the feature rather than to a component: saving to storage, keeping the URL in sync, listening for a shortcut.

Each one receives the value the graft returns, the same one use() gives, and returns nothing. TypeScript checks it against that value: an injected hook can't widen it.

Each entry runs in a component of its own that renders nothing, after the children and in the order of the array. It never wraps them, so it adds no node to the tree. Since it lives in the provider, an injected effect keeps running when the components below unmount: no component has to remember to call it.

Provider

type (props: TOptions & { children?: ReactNode }) => ReactNode

The component that runs the hook. Its props, without children, are passed to the hook as its options, so its type comes from the hook: currency is required here because useCart requires it.

Every provider is its own instance of the hook. Two providers on a page are two states, not one shared: mount one per feature, per item of a list, or at the root, as the state needs.

It renders no element: only the context, the children, then the injected hooks.

use

type () => TValue

Reads the value of the nearest provider above. It's a hook, so react-hooks/rules-of-hooks checks it like any other.

Outside a provider it throws, with the graft's name in the message, instead of handing back an empty default. The context itself is never exported: mounting the provider is the only way to supply a value.

The value is passed as the hook returns it, with no selectors or proxies: every component that calls use() re-renders when the provider does. Grafts are meant to be many and narrow, one per concern.

displayName

type string

The name the graft was given, or Graft without one. It's the same string you see in React DevTools and in the error of use(), handy when a tool or a log needs to tell grafts apart.

react-graft/hooks

Start with a hook that's ready

Dialogs, confirmations, countdowns, wizards: common bits of feature logic, ready to use. react-graft/hooks gives you plain hooks to pass to createGraft as graft; their options become the provider's props, just like your own hooks.

useGraftAlert

useGraftAlert<T>(): GraftAlert<T>

A confirmation you can await. open shows it and returns a promise that resolves with the answer: true when the user confirms, false when they dismiss it. The code that asked keeps reading top to bottom, with no callback passed down to the dialog.

The promise always settles. A new open while one is pending resolves the old one with false, and so does unmounting the provider: an await never hangs.

The payload of the last open stays in storage after closing, so the text doesn't vanish while the dialog animates out. A React event passed as payload becomes null, so open can go straight into onClick.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • isActiveboolean

    Whether the confirmation is open.

  • storageT | null

    The payload of the last open, or null. It stays after closing.

  • open(payload?: T | null) => Promise<boolean>

    Opens it with a payload, and returns a promise of the answer.

  • close(result?: boolean) => void

    Closes it and resolves the promise with result, false by default.

  • onConfirm() => void

    Closes it and resolves true: the confirm button.

  • onDismiss() => void

    Closes it and resolves false: the cancel button, the backdrop, Escape.

useGraftAuth

useGraftAuth<T = string>(options?: UseGraftAuthOptions<T>): GraftAuth<T>

A token, and whether there is one. isAuthorized is token !== null, so the whole app can switch between signed in and signed out from a single place.

It's state only: where the token is kept, in a cookie or in localStorage, is up to you. An injected hook is the natural place, as in the example: it runs inside the provider and follows every change of the token.

The type of the token is string by default; pass another one, such as an object with an expiry, as the type argument.

options

  • defaultValueT | nulldefault null

    The token on the first render, such as one read from a cookie on the server. null means signed out.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • tokenT | null

    The current token, or null.

  • isAuthorizedboolean

    Whether there is a token.

  • onAuth(token: T) => void

    Sets the token: call it after signing in.

  • onAuthRevoke() => void

    Sets it back to null: signing out.

useGraftCounter

useGraftCounter(options?: UseGraftCounterOptions): GraftCounter

A countdown in seconds, the kind behind a resend button. start counts down from duration, or from the seconds you pass, and the counter stops by itself at 0.

It counts against a deadline instead of subtracting one each second, so a background tab that throttles timers doesn't slow it down: when the user comes back, the number is right.

Calling start while it counts restarts it from the new value; start(0) does nothing. With startOnLoad it starts on mount, from defaultValue when given.

options

  • durationnumberdefault 30

    The seconds start counts down from.

  • defaultValuenumber | nulldefault null

    The seconds to count from on mount, read only with startOnLoad. null means duration.

  • startOnLoadbooleandefault false

    Starts counting as soon as the provider mounts.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • counternumber

    The seconds left, 0 when stopped.

  • durationnumber

    The duration option, to show the full time.

  • isCountingboolean

    Whether it's counting.

  • start(seconds?: number) => void

    Starts from seconds, duration by default.

  • reset() => void

    Stops and sets counter to 0.

useGraftDialog

useGraftDialog<T>(options?: UseGraftDialogOptions): GraftDialog<T>

The open state of a dialog, with a payload. The button that opens it and the dialog itself can live anywhere below the provider: a row of a list calls open(project), and the dialog reads the project from storage.

The payload lives in state, so calling open again on an open dialog re-renders it with the new payload. It stays in storage after closing, so the content doesn't vanish during the closing animation.

A React event passed as payload becomes null, so open can go straight into onClick. id is ready for aria-labelledby.

options

  • isActiveOnLoadbooleandefault false

    Starts open.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • isActiveboolean

    Whether the dialog is open.

  • storageT | null

    The payload of the last open, or null. It stays after closing.

  • open(payload?: T | null) => void

    Opens it with a payload.

  • close() => void

    Closes it.

useGraftPopover

useGraftPopover<T, E = unknown>(options?: UseGraftPopoverOptions): GraftPopover<T, E>

The same as useGraftDialog, plus anchorRef: a ref for the element the popover hangs from. Attach it to the trigger, and the popover, wherever it's rendered, can read where to place itself.

Positioning is up to you or to your popover component: the hook only holds the ref. Its second type argument is the anchor's type, such as HTMLButtonElement.

The payload works as in the dialog: the same trigger can open different menus with open("sort") or open("filter").

options

  • isActiveOnLoadbooleandefault false

    Starts open.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • isActiveboolean

    Whether the popover is open.

  • storageT | null

    The payload of the last open, or null. It stays after closing.

  • anchorRefRefObject<E | null>

    Attach it to the anchor element.

  • open(payload?: T | null) => void

    Opens it with a payload.

  • close() => void

    Closes it.

useGraftReload

useGraftReload(options?: UseGraftReloadOptions): GraftReload

A flag that turns on, then off again after a delay. Rendering a subtree only while isReloading is false unmounts it and mounts it again from scratch: a clean way to retry a component that failed, or to reset one with a lot of inner state.

onReload sets the flag, and a timeout clears it after delay milliseconds. Calling it again while reloading does nothing more.

options

  • delaynumberdefault 0

    Milliseconds isReloading stays true.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • isReloadingboolean

    Whether it's reloading.

  • onReload() => void

    Turns isReloading on.

useGraftStep

useGraftStep(options?: UseGraftStepOptions): GraftStep

A step number between bounds, for wizards, onboarding, carousels. onNext and onBack move by one, setStep jumps, and every move is clamped between min and max.

history keeps every step reached, in order, from the first: enough to know which steps the user has already seen. A move that doesn't change the step, such as onNext at max, adds nothing; going back adds the step reached, and nothing is ever trimmed.

options

  • defaultValuenumberdefault 0

    The first step.

  • minnumberdefault -Infinity

    The lowest step.

  • maxnumberdefault Infinity

    The highest step.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • stepnumber

    The current step.

  • minnumber

    The min option.

  • maxnumber

    The max option.

  • historyreadonly number[]

    Every step reached, in order, from the first.

  • setStep(step: number) => void

    Goes to a step, clamped.

  • onBack() => void

    One step back.

  • onNext() => void

    One step forward.

useGraftStore

useGraftStore<T>(options: UseGraftStoreOptions<T>): GraftStore<T>

A value with a setter and a reset: the general case, for anything that isn't one of the others, such as filters, a selection, a draft.

setValue is React's own setter, so it takes a value or an updater. resetValue goes back to the defaultValue of the first render: later changes of the prop are ignored.

defaultValue is required, so it's a required prop of the provider. Pass the type of the value as the type argument, such as useGraftStore<Filters>.

options

  • defaultValueTrequired

    The initial value, and the one resetValue goes back to.

returns

  • idstring

    From useId, stable for the life of the provider: use it to tie elements together with aria-* attributes.

  • valueT

    The current value.

  • setValueDispatch<SetStateAction<T>>

    Sets it, with a value or an updater.

  • resetValue() => void

    Back to defaultValue.

your turn

let's graft

nothing new to learn: it's just React