@open-pioneer/reactivity 4.9.0-dev.20260930055642 → 4.9.0-dev.20261029090037
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -1
- package/README.md +78 -0
- package/index.d.ts +1 -1
- package/index.js.map +1 -1
- package/package.json +3 -3
- package/skills/reactivity-react/SKILL.md +89 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
# @open-pioneer/reactivity
|
|
2
2
|
|
|
3
|
-
## 4.9.0-dev.
|
|
3
|
+
## 4.9.0-dev.20261029090037
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 0fba4d8: Ship an agent skill (`skills/reactivity-react/SKILL.md`) that explains how to read reactive state in React components with `useReactiveSnapshot` and the other hooks of this package.
|
|
8
|
+
With pnpm, approve the skill via `permissions` in `pnpm-workspace.yaml`; see the README section "Agent skill".
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- 42ca366: Update dependencies
|
|
4
13
|
|
|
5
14
|
## 4.8.0
|
|
6
15
|
|
package/README.md
CHANGED
|
@@ -93,6 +93,65 @@ function YourComponent({ signal }) {
|
|
|
93
93
|
|
|
94
94
|
More details are available in this package's API documentation and the [README of @conterra/reactivity-core](https://www.npmjs.com/package/@conterra/reactivity-core).
|
|
95
95
|
|
|
96
|
+
### Signals inside components
|
|
97
|
+
|
|
98
|
+
`useReactive(initialValue)` creates a signal that lives as long as the component, similar to `useState`.
|
|
99
|
+
The initial value is only used on the first render; later renders return the same signal instance.
|
|
100
|
+
Use it for local state that must feed into a `computed` or a model, for example a filter text that a model reads.
|
|
101
|
+
|
|
102
|
+
`useComputed(compute, deps)` creates a `computed` signal inside a component.
|
|
103
|
+
The signal is recreated when `deps` change, with the same rules for `deps` as in `useReactiveSnapshot`.
|
|
104
|
+
Use it when a child component, a model or another hook needs a signal instead of a plain value.
|
|
105
|
+
|
|
106
|
+
```tsx
|
|
107
|
+
import {
|
|
108
|
+
DISPATCH_SYNC,
|
|
109
|
+
useComputed,
|
|
110
|
+
useReactive,
|
|
111
|
+
useReactiveValue
|
|
112
|
+
} from "@open-pioneer/reactivity";
|
|
113
|
+
|
|
114
|
+
interface SearchProps {
|
|
115
|
+
model: Model;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function Search({ model }: SearchProps) {
|
|
119
|
+
const filter = useReactive("");
|
|
120
|
+
|
|
121
|
+
// Tracks `filter` and `model.items` (a reactive getter); recreated when `model` changes.
|
|
122
|
+
const matches = useComputed(
|
|
123
|
+
() => model.items.filter((item) => item.name.includes(filter.value)),
|
|
124
|
+
[model]
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
const filterText = useReactiveValue(filter, DISPATCH_SYNC);
|
|
128
|
+
const count = useReactiveValue(matches).length;
|
|
129
|
+
return (
|
|
130
|
+
<>
|
|
131
|
+
<input value={filterText} onChange={(e) => (filter.value = e.target.value)} />
|
|
132
|
+
<ResultList items={matches} />
|
|
133
|
+
<div>{count} matches</div>
|
|
134
|
+
</>
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Sync dispatch
|
|
140
|
+
|
|
141
|
+
By default, a component re-renders in a later macro task after a signal changed (`dispatch: "async"`), so several synchronous writes result in one render.
|
|
142
|
+
`useReactiveSnapshot` and `useReactiveValue` accept an `options` argument of type `ReactiveHookOptions` to change this.
|
|
143
|
+
Pass the constant `DISPATCH_SYNC` to re-render immediately after the signals were updated.
|
|
144
|
+
|
|
145
|
+
This is needed for controlled input fields, focus management and layout work, where React must see the new value in the same tick (see [issue #125](https://github.com/open-pioneer/trails-core-packages/issues/125)).
|
|
146
|
+
The `options` object should be constant or memoized, because a new object would re-subscribe on every render.
|
|
147
|
+
|
|
148
|
+
```tsx
|
|
149
|
+
import { DISPATCH_SYNC, useReactiveSnapshot } from "@open-pioneer/reactivity";
|
|
150
|
+
|
|
151
|
+
const text = useReactiveSnapshot(() => model.text, [model], DISPATCH_SYNC);
|
|
152
|
+
return <input value={text} onChange={(e) => model.setText(e.target.value)} />;
|
|
153
|
+
```
|
|
154
|
+
|
|
96
155
|
### ESLint configuration
|
|
97
156
|
|
|
98
157
|
You can use React's `exhaustive-deps` linting rule to check the dependencies of `useReactiveSnapshot` and `useComputed` (see [Documentation](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#advanced-configuration)).
|
|
@@ -116,6 +175,25 @@ Example:
|
|
|
116
175
|
}
|
|
117
176
|
```
|
|
118
177
|
|
|
178
|
+
## Agent skill
|
|
179
|
+
|
|
180
|
+
This package ships an agent skill (`skills/reactivity-react/SKILL.md`) that teaches AI coding agents how to use these hooks.
|
|
181
|
+
It builds on the `reactivity-core` skill shipped by `@conterra/reactivity-core`, so install both.
|
|
182
|
+
|
|
183
|
+
With pnpm >= 12.11, the skill is linked into your agent's skill directory automatically once approved (via `pnpm approve` or in `pnpm-workspace.yaml`).
|
|
184
|
+
See the [pnpm documentation](https://pnpm.io/agent-skills) for details.
|
|
185
|
+
|
|
186
|
+
```yaml
|
|
187
|
+
# pnpm-workspace.yaml
|
|
188
|
+
permissions:
|
|
189
|
+
"@conterra/reactivity-core":
|
|
190
|
+
skills: true
|
|
191
|
+
"@open-pioneer/reactivity":
|
|
192
|
+
skills: true
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Otherwise, copy or symlink `node_modules/@open-pioneer/reactivity/skills/reactivity-react` into your agent's skill directory (e.g. `.agents/skills/` or `.claude/skills/`).
|
|
196
|
+
|
|
119
197
|
## License
|
|
120
198
|
|
|
121
199
|
Apache-2.0 (see `LICENSE` file)
|
package/index.d.ts
CHANGED
|
@@ -62,7 +62,7 @@ export declare function useComputed<T>(compute: () => T, deps: DependencyList):
|
|
|
62
62
|
/**
|
|
63
63
|
* Advanced options for `useReactiveSnapshot`.
|
|
64
64
|
*
|
|
65
|
-
* Note that objects should either be memoized (`useMemo` etc.) or constants (see {@link DISPATCH_SYNC})
|
|
65
|
+
* Note that objects should either be memoized (`useMemo` etc.) or constants (see {@link DISPATCH_SYNC}).
|
|
66
66
|
*/
|
|
67
67
|
export interface ReactiveHookOptions {
|
|
68
68
|
dispatch?: DispatchType;
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023-2025 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n DispatchType,\n Reactive,\n ReadonlyReactive,\n computed,\n reactive,\n watchValue\n} from \"@conterra/reactivity-core\";\nimport {\n DependencyList,\n useCallback,\n useDebugValue,\n useMemo,\n useRef,\n useSyncExternalStore\n} from \"react\";\n\n/**\n * Creates a new signal with the initial value `undefined`.\n *\n * The initial value will only be applied on the very first call to this hook.\n * The same signal instance will be returned when this hook is called on the next render.\n * This is very similar (in concept) to React's builtin `useState` hook.\n *\n * @example\n *\n * ```jsx\n * function YourComponent() {\n * const mySignal = useReactive();\n * const someEventHandler = () => {\n * // Update the value after some event\n * mySignal.value = \"new value\";\n * };\n *\n * // Always returns the current value, re-renders if necessary.\n * const currentValue = useReactiveValue(mySignal);\n * }\n * ```\n */\nexport function useReactive<T>(): Reactive<T | undefined>;\n\n/**\n * Creates a new signal with the given initial value.\n *\n * @see {@link useReactive()}.\n */\nexport function useReactive<T>(initialValue: T): Reactive<T>;\n\nexport function useReactive<T>(initialValue?: T): Reactive<T | undefined> {\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => reactive(initialValue), []);\n}\n\n/**\n * Creates a new computed signal that evaluates the given `compute` function.\n *\n * The hook returns the same signal for as long as `deps` remains the same.\n * When `deps` change, a new signal will be created.\n *\n * @example\n *\n * Defining a simple computed value in your react component:\n *\n * ```jsx\n * function MyComponent(props) {\n * // Creates a computed value based on the given function.\n * // The computed value will be re-created whenever one of the listed dependencies changes.\n * // While the computed value can track all its _reactive_ dependencies automatically (`.value` reads etc.)\n * // the reactive value itself used here might change (different props) - this cannot be detected automatically.\n * const computed = useComputed(() => props.someReactive.value * 2, [props.someReactive]);\n *\n * // Watches on `computed` and returns its current value.\n * const currentValue = useReactiveValue(computed);\n * }\n * ```\n *\n * > If the body of your compute function depends on non-reactive values (such as react props or state),\n * > list those values in the `deps` array.\n *\n * @see {@link useReactiveValue()}\n * @see {@link useReactiveSnapshot()}\n */\nexport function useComputed<T>(compute: () => T, deps: DependencyList): ReadonlyReactive<T> {\n const computeRef = useRef(compute);\n\n // oxlint-disable-next-line react/refs\n computeRef.current = compute;\n\n return useMemo(() => {\n // not really used, but computed must be recreated when this value changes\n void deps;\n\n return computed(() => computeRef.current());\n // oxlint-disable-next-line react/use-memo react-hooks/exhaustive-deps\n }, deps);\n}\n\n/**\n * Advanced options for `useReactiveSnapshot`.\n *\n * Note that objects should either be memoized (`useMemo` etc.) or constants (see {@link DISPATCH_SYNC})
|
|
1
|
+
{"version":3,"file":"index.js","sources":["index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023-2025 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n DispatchType,\n Reactive,\n ReadonlyReactive,\n computed,\n reactive,\n watchValue\n} from \"@conterra/reactivity-core\";\nimport {\n DependencyList,\n useCallback,\n useDebugValue,\n useMemo,\n useRef,\n useSyncExternalStore\n} from \"react\";\n\n/**\n * Creates a new signal with the initial value `undefined`.\n *\n * The initial value will only be applied on the very first call to this hook.\n * The same signal instance will be returned when this hook is called on the next render.\n * This is very similar (in concept) to React's builtin `useState` hook.\n *\n * @example\n *\n * ```jsx\n * function YourComponent() {\n * const mySignal = useReactive();\n * const someEventHandler = () => {\n * // Update the value after some event\n * mySignal.value = \"new value\";\n * };\n *\n * // Always returns the current value, re-renders if necessary.\n * const currentValue = useReactiveValue(mySignal);\n * }\n * ```\n */\nexport function useReactive<T>(): Reactive<T | undefined>;\n\n/**\n * Creates a new signal with the given initial value.\n *\n * @see {@link useReactive()}.\n */\nexport function useReactive<T>(initialValue: T): Reactive<T>;\n\nexport function useReactive<T>(initialValue?: T): Reactive<T | undefined> {\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => reactive(initialValue), []);\n}\n\n/**\n * Creates a new computed signal that evaluates the given `compute` function.\n *\n * The hook returns the same signal for as long as `deps` remains the same.\n * When `deps` change, a new signal will be created.\n *\n * @example\n *\n * Defining a simple computed value in your react component:\n *\n * ```jsx\n * function MyComponent(props) {\n * // Creates a computed value based on the given function.\n * // The computed value will be re-created whenever one of the listed dependencies changes.\n * // While the computed value can track all its _reactive_ dependencies automatically (`.value` reads etc.)\n * // the reactive value itself used here might change (different props) - this cannot be detected automatically.\n * const computed = useComputed(() => props.someReactive.value * 2, [props.someReactive]);\n *\n * // Watches on `computed` and returns its current value.\n * const currentValue = useReactiveValue(computed);\n * }\n * ```\n *\n * > If the body of your compute function depends on non-reactive values (such as react props or state),\n * > list those values in the `deps` array.\n *\n * @see {@link useReactiveValue()}\n * @see {@link useReactiveSnapshot()}\n */\nexport function useComputed<T>(compute: () => T, deps: DependencyList): ReadonlyReactive<T> {\n const computeRef = useRef(compute);\n\n // oxlint-disable-next-line react/refs\n computeRef.current = compute;\n\n return useMemo(() => {\n // not really used, but computed must be recreated when this value changes\n void deps;\n\n return computed(() => computeRef.current());\n // oxlint-disable-next-line react/use-memo react-hooks/exhaustive-deps\n }, deps);\n}\n\n/**\n * Advanced options for `useReactiveSnapshot`.\n *\n * Note that objects should either be memoized (`useMemo` etc.) or constants (see {@link DISPATCH_SYNC}).\n */\nexport interface ReactiveHookOptions {\n dispatch?: DispatchType;\n}\n\n/**\n * Switches from async dispatch (the default) to sync dispatch.\n *\n * This is helpful when using reactive values for input fields, focus management or layout behavior.\n */\nexport const DISPATCH_SYNC: ReactiveHookOptions = Object.freeze({ dispatch: \"sync\" });\n\n/**\n * Watches the given reactive object and returns its current value.\n *\n * > NOTE: The return value of this hook should be considered read-only.\n *\n * > NOTE: The `options` parameter (if used) should be memoized or constant.\n *\n * @see {@link useComputed()}\n */\nexport function useReactiveValue<T>(\n reactive: ReadonlyReactive<T>,\n options?: ReactiveHookOptions\n): T {\n const getSnapshot = useCallback(() => {\n return reactive.peek();\n }, [reactive]);\n const subscribe = useCallback(\n (cb: () => void) => {\n const handle = watchValue(() => reactive.value, cb, {\n dispatch: options?.dispatch ?? \"async\"\n });\n return () => handle.destroy();\n },\n [reactive, options?.dispatch]\n );\n const value = useSyncExternalStore(subscribe, getSnapshot);\n useDebugValue(value);\n return value;\n}\n\n/**\n * Evaluates the `compute` function and returns its result.\n *\n * The body of the compute function is tracked: it\n * will be re-evaluated whenever its reactive dependencies change.\n * The outer react component will re-render whenever `compute` returns a new value.\n *\n * > NOTE: The return value of this hook should be considered read-only.\n *\n * > NOTE: The `options` parameter (if used) should be memoized or constant.\n *\n * @example\n *\n * Simple Example:\n *\n * ```jsx\n * import { useReactiveSnapshot } from \"@open-pioneer/reactivity\";\n *\n * // A reactive signal from anywhere (global data, props, ...).\n * const name = reactive(\"User\");\n *\n * function YourComponent() {\n * const nameSnapshot = useReactiveSnapshot(() => name.value);\n * // snapshot is automatically up to date\n * }\n * ```\n *\n * @example\n *\n * Multiple values, with props:\n *\n * ```jsx\n * import { useReactiveSnapshot } from \"@open-pioneer/reactivity\";\n *\n * function YourComponent({firstName, lastName}) {\n * // You can use complex expressions in your compute function,\n * // just like in a computed signal.\n * // React-dependencies used in the callback must be listed in the second argument,\n * // just like when using `useMemo()` or `useEffect`.\n * const snapshot = useReactiveSnapshot(() => {\n * return {\n * firstName: firstName.value,\n * lastName: lastName.value,\n * fullName: `${firstName.value} ${lastName.value}`\n * };\n * }, [firstName, lastName]);\n * // snapshot.firstName, snapshot.lastName, snapshot.fullName are available and up to date\n * }\n * ```\n *\n * @example\n *\n * Changing the default timing:\n *\n * ```jsx\n * import { useReactiveSnapshot, DISPATCH_SYNC } from \"@open-pioneer/reactivity\";\n *\n * function YourComponent(props) {\n * // DISPATCH_SYNC rerenders us faster than the default timing.\n * // This is useful for values used in input fields, in layout operations or focus management.\n * // See also https://github.com/open-pioneer/trails-core-packages/issues/125\n * const nameSnapshot = useReactiveSnapshot(() => props.reactiveModel.value, [props.reactiveModel], DISPATCH_SYNC);\n * }\n * ```\n *\n * @see\n * This hook is based on {@link useComputed()} and {@link useReactiveValue()}.\n */\nexport function useReactiveSnapshot<T>(\n compute: () => T,\n deps: DependencyList,\n options?: ReactiveHookOptions\n): T {\n // We create an internal computed value that executes the compute function;\n // this way the implementation of `compute` is automatically tracked.\n // getSnapshot and subscribe simply watch the current value of that computed value.\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n const computedSnapshot = useComputed(compute, deps);\n const snapshot = useReactiveValue(computedSnapshot, options);\n useDebugValue(snapshot);\n return snapshot;\n}\n"],"names":["reactive"],"mappings":";;;AAmDO,SAAS,YAAe,YAAA,EAA2C;AAEtE,EAAA,OAAO,QAAQ,MAAM,QAAA,CAAS,YAAY,CAAA,EAAG,EAAE,CAAA;AACnD;AA+BO,SAAS,WAAA,CAAe,SAAkB,IAAA,EAA2C;AACxF,EAAA,MAAM,UAAA,GAAa,OAAO,OAAO,CAAA;AAGjC,EAAA,UAAA,CAAW,OAAA,GAAU,OAAA;AAErB,EAAA,OAAO,QAAQ,MAAM;AAIjB,IAAA,OAAO,QAAA,CAAS,MAAM,UAAA,CAAW,OAAA,EAAS,CAAA;AAAA,EAE9C,GAAG,IAAI,CAAA;AACX;AAgBO,MAAM,gBAAqC,MAAA,CAAO,MAAA,CAAO,EAAE,QAAA,EAAU,QAAQ;AAW7E,SAAS,gBAAA,CACZA,WACA,OAAA,EACC;AACD,EAAA,MAAM,WAAA,GAAc,YAAY,MAAM;AAClC,IAAA,OAAOA,UAAS,IAAA,EAAK;AAAA,EACzB,CAAA,EAAG,CAACA,SAAQ,CAAC,CAAA;AACb,EAAA,MAAM,SAAA,GAAY,WAAA;AAAA,IACd,CAAC,EAAA,KAAmB;AAChB,MAAA,MAAM,MAAA,GAAS,UAAA,CAAW,MAAMA,SAAAA,CAAS,OAAO,EAAA,EAAI;AAAA,QAChD,QAAA,EAAU,SAAS,QAAA,IAAY;AAAA,OAClC,CAAA;AACD,MAAA,OAAO,MAAM,OAAO,OAAA,EAAQ;AAAA,IAChC,CAAA;AAAA,IACA,CAACA,SAAAA,EAAU,OAAA,EAAS,QAAQ;AAAA,GAChC;AACA,EAAA,MAAM,KAAA,GAAQ,oBAAA,CAAqB,SAAA,EAAW,WAAW,CAAA;AACzD,EAAA,aAAA,CAAc,KAAK,CAAA;AACnB,EAAA,OAAO,KAAA;AACX;AAsEO,SAAS,mBAAA,CACZ,OAAA,EACA,IAAA,EACA,OAAA,EACC;AAKD,EAAA,MAAM,gBAAA,GAAmB,WAAA,CAAY,OAAA,EAAS,IAAI,CAAA;AAClD,EAAA,MAAM,QAAA,GAAW,gBAAA,CAAiB,gBAAA,EAAkB,OAAO,CAAA;AAC3D,EAAA,aAAA,CAAc,QAAQ,CAAA;AACtB,EAAA,OAAO,QAAA;AACX;;"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@open-pioneer/reactivity",
|
|
4
|
-
"version": "4.9.0-dev.
|
|
4
|
+
"version": "4.9.0-dev.20261029090037",
|
|
5
5
|
"description": "Provides integration for the reactivity API.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"open-pioneer-trails"
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
"directory": "src/packages/reactivity"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@conterra/reactivity-core": "^0.8.
|
|
18
|
-
"react": "^19.3.
|
|
17
|
+
"@conterra/reactivity-core": "^0.8.9",
|
|
18
|
+
"react": "^19.3.1"
|
|
19
19
|
},
|
|
20
20
|
"publishConfig": {
|
|
21
21
|
"directory": "dist",
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: reactivity-react
|
|
3
|
+
description: How to render state from @conterra/reactivity-core signals in React with @open-pioneer/reactivity (useReactiveSnapshot, useReactiveValue, useComputed, useReactive, DISPATCH_SYNC). Use when writing or reviewing React components that read signals, models or Trails services, or when deciding whether component state belongs in React state or in signals.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @open-pioneer/reactivity
|
|
7
|
+
|
|
8
|
+
React hooks that subscribe a component to signals from `@conterra/reactivity-core`.
|
|
9
|
+
For signals, `computed`, `batch`, dispatch and timing see the `reactivity-core` skill.
|
|
10
|
+
|
|
11
|
+
Full documentation: `node_modules/@open-pioneer/reactivity/README.md`.
|
|
12
|
+
API docs are in the type declarations (`node_modules/@open-pioneer/reactivity/index.d.ts`).
|
|
13
|
+
|
|
14
|
+
## Where state lives
|
|
15
|
+
|
|
16
|
+
- State owned by a service or model, or derived from it, lives in signals and reaches components through `useReactiveSnapshot`.
|
|
17
|
+
- Local UI state of one component, or of a few plain UI components, may stay in React state or context.
|
|
18
|
+
- Reactive values enter a component only through the hooks below; copying them into React state is a bug (see [Common mistakes](#common-mistakes)).
|
|
19
|
+
|
|
20
|
+
## useReactiveSnapshot
|
|
21
|
+
|
|
22
|
+
```tsx
|
|
23
|
+
import { useReactiveSnapshot } from "@open-pioneer/reactivity";
|
|
24
|
+
|
|
25
|
+
interface GreetingProps {
|
|
26
|
+
model: Model;
|
|
27
|
+
greeting: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// `model.firstName` and `model.lastName` are getters backed by signals (see the reactivity-core skill).
|
|
31
|
+
function Greeting({ model, greeting }: GreetingProps) {
|
|
32
|
+
const text = useReactiveSnapshot(
|
|
33
|
+
() => `${greeting} ${model.firstName} ${model.lastName}`,
|
|
34
|
+
[model, greeting]
|
|
35
|
+
);
|
|
36
|
+
return <div>{text}</div>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Services are read the same way (themeService from useService()).
|
|
40
|
+
const colorMode = useReactiveSnapshot(() => themeService.colorMode, [themeService]);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- The callback is tracked like a `computed`: it re-runs when a signal it read changes, and the component re-renders when the result changes (`Object.is`).
|
|
44
|
+
- Keep the callback pure. It may run any number of times, so writes and side effects belong in event handlers or model methods.
|
|
45
|
+
- Return an object or array to read several values with one hook, or use multiple hooks.
|
|
46
|
+
|
|
47
|
+
### Dependencies
|
|
48
|
+
|
|
49
|
+
The hook tracks reads of reactive data: signal `.value` reads and getters backed by signals.
|
|
50
|
+
Everything else the callback reads is non-reactive data in terms of the reactivity API: props, React state, context, results of `useService()`, local variables.
|
|
51
|
+
List all non-reactive data in `deps`, including the model or service object whose getters you read.
|
|
52
|
+
Never list the reactive values themselves.
|
|
53
|
+
The lint rule `react-hooks/exhaustive-deps` checks `deps` once it is configured with `additionalHooks`; see README section `### ESLint configuration`.
|
|
54
|
+
|
|
55
|
+
## Other hooks
|
|
56
|
+
|
|
57
|
+
- `useReactiveValue(signal)`: one signal at hand, nothing to compute. Same as `useReactiveSnapshot(() => signal.value, [signal])`.
|
|
58
|
+
- `useComputed(compute, deps)`: a `computed` signal created inside a component, for passing to children, models or other hooks. Same `deps` rule.
|
|
59
|
+
- `useReactive(initialValue)`: a signal that lives as long as the component, like `useState`. For local state that must feed into a `computed` or a model.
|
|
60
|
+
- `DISPATCH_SYNC` as the `options` argument of `useReactiveSnapshot` or `useReactiveValue`: the component re-renders synchronously with the write. For controlled inputs, focus management and layout; the async default fits everything else.
|
|
61
|
+
|
|
62
|
+
## Common mistakes
|
|
63
|
+
|
|
64
|
+
- Reading a getter or `.value` in the render body outside a hook: the read is not tracked, so the component shows a stale value.
|
|
65
|
+
|
|
66
|
+
```tsx
|
|
67
|
+
// Wrong
|
|
68
|
+
return <div>{model.firstName}</div>;
|
|
69
|
+
|
|
70
|
+
// Right
|
|
71
|
+
const firstName = useReactiveSnapshot(() => model.firstName, [model]);
|
|
72
|
+
return <div>{firstName}</div>;
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- Missing `deps`: the callback keeps reading an old prop, service or model.
|
|
76
|
+
- Writing signals or running side effects inside the callback; move them to event handlers, model methods or `useEffect` on the snapshot.
|
|
77
|
+
- Mirroring a reactive value into React state. Render the snapshot directly.
|
|
78
|
+
|
|
79
|
+
```tsx
|
|
80
|
+
// Wrong
|
|
81
|
+
const [name, setName] = useState(model.firstName);
|
|
82
|
+
useEffect(() => setName(model.firstName), [model.firstName]);
|
|
83
|
+
|
|
84
|
+
// Right
|
|
85
|
+
const name = useReactiveSnapshot(() => model.firstName, [model]);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- An inline options object such as `{ dispatch: "sync" }` re-subscribes on every render. Pass the constant `DISPATCH_SYNC` or memoize the object.
|
|
89
|
+
- `DISPATCH_SYNC` as the default. It causes redundant renders; reserve it for inputs, focus and layout.
|