createHook() function
Home > @rimitive/react > createHook
createHook() function
Section titled “createHook() function”Create a React hook from a double-function behavior pattern.
This is designed for portable headless components that follow the pattern: (svc) => (...args) => Result
The returned hook handles svc injection automatically and creates a memoized behavior instance.
Note: Arguments are captured once when the component mounts (like useRef’s initial value). If you need reactive options, pass signals as option values and read them inside the behavior.
Signature:
export declare function createHook<TSvc extends ReactiveSvc, Args extends unknown[], Result>(behavior: (svc: TSvc) => (...args: Args) => Result): (...args: Args) => Result;Parameters
Section titled “Parameters”|
Parameter |
Type |
Description |
|---|---|---|
|
behavior |
(svc: TSvc) => (…args: Args) => Result |
Returns:
(…args: Args) => Result
Example 1
Section titled “Example 1”// Define a portable behaviorconst useCounter = createHook((svc) => (initialValue: number) => { const count = svc.signal(initialValue); const increment = () => count(count() + 1); return { count, increment };});
// Use it in a componentfunction Counter() { const { count, increment } = useCounter(0); const value = useSubscribe(count); return <button onClick={increment}>Count: {value}</button>;}Example 2
Section titled “Example 2”// With reactive options via signalsconst useTimer = createHook((svc) => (interval: Readable<number>) => { const elapsed = svc.signal(0); svc.effect(() => { const timer = setInterval(() => { elapsed(elapsed() + 1); }, interval()); return () => clearInterval(timer); }); return elapsed;});