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
The **atomTree** utility provides a hierarchical way to create, reuse, and remove Jotai atoms. Each atom is associated with a unique path, which is an array of unknown types. When you request the same path multiple times, `atomTree` ensures that the same atom instance is returned. You can also remove a specific atom or an entire subtree of atoms when they are no longer needed.
118
+
119
+
Use `atomTree` when you anticipate a large number of potential paths and want to:
120
+
121
+
-**Reuse the same atom** for repeated paths.
122
+
-**Clean up** unwanted atoms easily, including entire subtrees.
123
+
124
+
```js
125
+
import { atom } from'jotai'
126
+
import { atomTree } from'jotai-family'
127
+
128
+
// Create a tree instance, passing a factory function
129
+
// that takes a path array and returns a new atom.
130
+
consttree=atomTree((path) =>atom(path.join('-')))
131
+
132
+
// Create or retrieve the atom at ['foo', 'bar']
133
+
constatomA=tree(['foo', 'bar'])
134
+
constatomB=tree(['foo', 'bar'])
135
+
136
+
// atomA and atomB are the same instance.
137
+
console.log(atomA === atomB) // true
138
+
139
+
// Remove the atom at ['foo', 'bar']
140
+
// (and optionally remove its entire subtree)
141
+
tree.remove(['foo', 'bar'])
142
+
```
143
+
144
+
### API
145
+
146
+
#### Creating the tree
147
+
148
+
Creates a new hierarchical tree of Jotai atoms. It accepts a **initializePathAtom** function that receives a path array and returns an atom. The returned function can be used to create, retrieve, and remove atoms at specific paths.
149
+
150
+
```ts
151
+
function atomTree<Path, AtomType>(
152
+
initializePathAtom: (path:Path) =>AtomType
153
+
): {
154
+
(path:Path):AtomType
155
+
remove(path:Path, removeSubTree?:boolean):void
156
+
getSubTree(path:Path):Node<AtomType> |undefined
157
+
getNodePath(path:Path):Node<AtomType>[]
158
+
}
159
+
160
+
typeNode<AtomType> = {
161
+
atom?:AtomType
162
+
children?:Map<PathSegment, Node<AtomType>>
163
+
}
164
+
```
165
+
166
+
### Creating Path Atoms
167
+
```ts
168
+
tree(path:Path):AtomType
169
+
```
170
+
Creates (or retrieves) an atom at the specified path. Subsequent calls with the same path return the same atom instance.
171
+
172
+
### Removing Path Atoms
173
+
```ts
174
+
tree.remove(path:Path, removeSubTree=false):void
175
+
```
176
+
Removes the atom at the specified path. If `removeSubTree` is `true`, all child paths under that path are also removed.
177
+
178
+
This method removes the atom at the specified path. If `removeSubTree` is `true`, it also removes all child paths under that path.
0 commit comments