use-context-selectors
v0.1.0
Published
Call multiple useContextSelector hooks with one tuple-typed API.
Maintainers
Readme
use-context-selectors
Call several useContextSelector hooks in one expression, with tuple-typed results that line up with your selectors.
This package re-exports the full public API of use-context-selector. It is a peer dependency, so you install it alongside this package — that way you control the version and avoid duplicate copies in your bundle.
Installation
pnpm add use-context-selectors use-context-selector
# or: npm install use-context-selectors use-context-selectorPeer dependencies: React 18+, scheduler 0.19+, and use-context-selector 2+.
pnpm add react schedulerIn many apps, scheduler is already satisfied transitively (for example via react-dom). If the bundler reports a missing scheduler module, add it explicitly.
Usage
Import context helpers from this package, then pass a context and one or more selectors to useContextSelectors. You get an array of selected values in the same order as the selectors, with types inferred from each selector’s return type.
import { createContext, useContextSelectors } from "use-context-selectors";
type Store = { count: number; label: string };
const StoreContext = createContext<Store>({ count: 0, label: "" });
function Counter() {
const [count, label] = useContextSelectors(
StoreContext,
(s) => s.count,
(s) => s.label,
);
return (
<button type="button">
{label}: {count}
</button>
);
}That is equivalent to calling useContextSelector once per selector, but keeps selectors and results grouped and easier to refactor.
Re-exports
Everything exported by use-context-selector is also re-exported from use-context-selectors (for example createContext, useContextSelector, useContext, useContextUpdate, BridgeProvider, useBridgeValue). You can import those symbols from either package — both resolve to the same installed copy of use-context-selector.
API
useContextSelectors(context, ...selectors)
- context — A
Contextcreated withcreateContextfrom this package (or the same API as upstream). - selectors — One or more functions
(value) => selectedwherevalueis the context’s current value.
Returns: A tuple (array) whose element types are the return types of the selectors, in order.
Each selector still runs under the same rules as upstream: the component re-renders only when the selected slice changes (by Object.is).
ContextType<C>
Utility type: the value type held by a given context C (the infer partner to your context generic).
import type { Context, ContextType } from "use-context-selectors";
declare const MyContext: Context<MyState>;
type State = ContextType<typeof MyContext>;Development
This repo uses Vite+ (vp).
- Install dependencies:
vp install - Format, lint, and typecheck:
vp check - Tests:
vp test - Build the library:
vp pack
License
MIT
