You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/en/guide/v10/signals.md
+227Lines changed: 227 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -693,3 +693,230 @@ function Component() {
693
693
);
694
694
}
695
695
```
696
+
697
+
## Models
698
+
699
+
Models provide a structured way to build reactive state containers that encapsulate signals, computed values, effects, and actions. They offer a clean pattern for organizing complex state logic while ensuring automatic cleanup and batched updates.
700
+
701
+
### createModel(factory)
702
+
703
+
The `createModel(factory)` function creates a model constructor from a factory function. The factory function can accept arguments for initialization and should return an object containing signals, computed values, and action methods.
counter.increment(); // Updates are automatically batched
731
+
console.log(counter.count.value); // 6
732
+
console.log(counter.doubled.value); // 12
733
+
734
+
// Clean up all effects when done
735
+
counter[Symbol.dispose]();
736
+
```
737
+
738
+
#### Key Features
739
+
740
+
- **Factory arguments**: Factory functions can accept arguments for initialization, making models reusable with different configurations.
741
+
- **Automatic batching**: All methods returned from the factory are automatically wrapped as actions, meaning state updates within them are batched and untracked.
742
+
- **Automatic effect cleanup**: Effects created during model construction are captured and automatically disposed when the model is disposed via `Symbol.dispose`.
743
+
- **Composable models**: Models compose naturally - effects from nested models are captured by the parent and disposed together when the parent is disposed.
744
+
745
+
#### Model Composition
746
+
747
+
Models can be nested within other models. When a parent model is disposed, all effects from nested models are automatically cleaned up:
748
+
749
+
```js
750
+
constTodoItemModel=createModel((text) => {
751
+
constcompleted=signal(false);
752
+
753
+
return {
754
+
text,
755
+
completed,
756
+
toggle() {
757
+
completed.value=!completed.value;
758
+
}
759
+
};
760
+
});
761
+
762
+
constTodoListModel=createModel(() => {
763
+
constitems=signal([]);
764
+
765
+
return {
766
+
items,
767
+
addTodo(text) {
768
+
consttodo=newTodoItemModel(text);
769
+
items.value= [...items.value, todo];
770
+
},
771
+
removeTodo(todo) {
772
+
items.value=items.value.filter(t=> t !== todo);
773
+
todo[Symbol.dispose]();
774
+
}
775
+
};
776
+
});
777
+
778
+
consttodoList=newTodoListModel();
779
+
todoList.addTodo('Buy groceries');
780
+
todoList.addTodo('Walk the dog');
781
+
782
+
// Disposing the parent also cleans up all nested model effects
783
+
todoList[Symbol.dispose]();
784
+
```
785
+
786
+
### action(fn)
787
+
788
+
The `action(fn)` function wraps a function to run in a batched and untracked context. This is useful when you need to create standalone actions outside of a model:
The `useModel` hook is available in both `@preact/signals` and `@preact/signals-react` packages. It handles creating a model instance on first render, maintaining the same instance across re-renders, and automatically disposing the model when the component unmounts.
counter.count.value=10; // TypeScript error: Cannot assign to 'value'
885
+
```
886
+
887
+
#### Custom Dispose Logic
888
+
889
+
If your model needs custom cleanup logic that isn't related to signals (such as closing WebSocket connections), use an effect with no dependencies that returns a cleanup function:
890
+
891
+
```js
892
+
constWebSocketModel=createModel((url) => {
893
+
constmessages=signal([]);
894
+
constws=newWebSocket(url);
895
+
896
+
ws.onmessage= (e) => {
897
+
messages.value= [...messages.value, e.data];
898
+
};
899
+
900
+
// This effect runs once; its cleanup runs on dispose
This pattern mirrors `useEffect(() => { return cleanup }, [])` in React and ensures that cleanup happens automatically when models are composed together - parent models don't need to know about the dispose functions of nested models.
0 commit comments