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: apps/docs/pages/store/reading-state.mdx
+36-1Lines changed: 36 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -44,6 +44,18 @@ function Counter() {
44
44
necessary, as it may lead to excessive re-renders and performance issues.
45
45
</Callout>
46
46
47
+
###Using`use` with selector
48
+
49
+
You can pass a selector function as the first parameter of use to only subscribe to a subsect of that state.
50
+
51
+
This is useful for optimizing performance eg for long lists.
52
+
53
+
```tsx
54
+
const activeTodo=todosStore.use((todos)=> {
55
+
returntodos.find((todo)=>todo.id===activeTodoId);
56
+
});
57
+
```
58
+
47
59
###Nested Methods
48
60
49
61
You can use the`get` and`use` methods to access deeply nested state properties.
@@ -86,9 +98,32 @@ In this example, the `UserProfile` component only subscribes to changes in the `
86
98
87
99
##Computed Properties
88
100
89
-
Computed properties, defined using the`computed` method, can also be accessed using`get` and`use`. However, they cannot be directly modified using`set` or`assign`.
101
+
Computed properties, defined using the`computed` method, can also be accessed using`get` and`use`.
90
102
91
103
```tsx
92
104
const fullName=userStore.fullName.get();
93
105
const fullName=userStore.fullName.use();
94
106
```
107
+
108
+
###Example computed values with read/write
109
+
110
+
```tsx
111
+
const countStore=store({ count:0 })
112
+
.computed((store)=> ({
113
+
doubled: {
114
+
// optional input here
115
+
read: ()=>store.count.use()*2,
116
+
write: (value:number)=>store.count.set(value/2),
117
+
},
118
+
}))
119
+
.actions((store)=> ({
120
+
increment() {
121
+
store.count.set(store.count.get()+1);
122
+
},
123
+
decrement() {
124
+
store.count.set(store.count.get()-1);
125
+
},
126
+
}));
127
+
```
128
+
129
+
Note: inputs are optional for both read/write and strongly typed.