0
# Core Atoms
1
2
Core atom functionality providing the fundamental building blocks for state management in Jotai. Atoms are the basic units of state that can hold values, compute derived values, or perform actions.
3
4
## Capabilities
5
6
### Atom Creation Function
7
8
Creates atoms with different behaviors based on the arguments provided.
9
10
```typescript { .api }
11
/**
12
* Create a primitive atom with an initial value
13
* @param initialValue - The initial value for the atom
14
* @returns PrimitiveAtom that can be read and written
15
*/
16
function atom<Value>(initialValue: Value): PrimitiveAtom<Value>;
17
18
/**
19
* Create a primitive atom without an initial value
20
* @returns PrimitiveAtom with undefined initial value
21
*/
22
function atom<Value>(): PrimitiveAtom<Value | undefined>;
23
24
/**
25
* Create a read-only derived atom
26
* @param read - Function to compute the atom's value from other atoms
27
* @returns Read-only Atom
28
*/
29
function atom<Value>(read: Read<Value>): Atom<Value>;
30
31
/**
32
* Create a writable derived atom with custom read and write logic
33
* @param read - Function to compute the atom's value from other atoms
34
* @param write - Function to handle write operations
35
* @returns WritableAtom with custom behavior
36
*/
37
function atom<Value, Args extends unknown[], Result>(
38
read: Read<Value, SetAtom<Args, Result>>,
39
write: Write<Args, Result>
40
): WritableAtom<Value, Args, Result>;
41
42
/**
43
* Create a primitive atom with custom write behavior
44
* @param initialValue - The initial value for the atom
45
* @param write - Custom write function
46
* @returns WritableAtom with custom write behavior
47
*/
48
function atom<Value, Args extends unknown[], Result>(
49
initialValue: Value,
50
write: Write<Args, Result>
51
): WritableAtom<Value, Args, Result>;
52
```
53
54
**Usage Examples:**
55
56
```typescript
57
import { atom } from "jotai";
58
59
// Primitive atom
60
const countAtom = atom(0);
61
62
// Derived read-only atom
63
const doubleCountAtom = atom((get) => get(countAtom) * 2);
64
65
// Write-only atom (action)
66
const incrementAtom = atom(null, (get, set) => {
67
set(countAtom, get(countAtom) + 1);
68
});
69
70
// Writable derived atom
71
const uppercaseAtom = atom(
72
(get) => get(textAtom).toUpperCase(),
73
(get, set, newText: string) => {
74
set(textAtom, newText.toLowerCase());
75
}
76
);
77
78
// Async atom
79
const userAtom = atom(async () => {
80
const response = await fetch("/api/user");
81
return response.json();
82
});
83
```
84
85
## Core Interfaces and Types
86
87
### Atom Interface
88
89
Base interface for all atoms.
90
91
```typescript { .api }
92
interface Atom<Value> {
93
/** Returns a string representation of the atom */
94
toString: () => string;
95
/** Function to read the atom's value */
96
read: Read<Value>;
97
/** Optional function to compare atoms for equality */
98
unstable_is?(atom: Atom<unknown>): boolean;
99
/** Optional debug label for development */
100
debugLabel?: string;
101
/** Internal flag for marking atoms as private */
102
debugPrivate?: boolean;
103
/** Optional initialization callback when atom is first referenced */
104
unstable_onInit?(store: Store): void;
105
}
106
```
107
108
### WritableAtom Interface
109
110
Interface for atoms that can be written to.
111
112
```typescript { .api }
113
interface WritableAtom<Value, Args extends unknown[], Result> extends Atom<Value> {
114
/** Function to read the atom's value with setSelf capability */
115
read: Read<Value, SetAtom<Args, Result>>;
116
/** Function to handle write operations */
117
write: Write<Args, Result>;
118
/** Optional mount callback for side effects */
119
onMount?: OnMount<Args, Result>;
120
}
121
```
122
123
### PrimitiveAtom Type
124
125
Type alias for simple readable and writable atoms.
126
127
```typescript { .api }
128
type PrimitiveAtom<Value> = WritableAtom<Value, [SetStateAction<Value>], void>;
129
```
130
131
## Function Types
132
133
### Read Function Type
134
135
Function type for reading atom values.
136
137
```typescript { .api }
138
type Read<Value, SetSelf = never> = (
139
get: Getter,
140
options: {
141
readonly signal: AbortSignal;
142
readonly setSelf: SetSelf
143
}
144
) => Value;
145
```
146
147
### Write Function Type
148
149
Function type for writing to atoms.
150
151
```typescript { .api }
152
type Write<Args extends unknown[], Result> = (
153
get: Getter,
154
set: Setter,
155
...args: Args
156
) => Result;
157
```
158
159
### OnMount Function Type
160
161
Function type for mount callbacks.
162
163
```typescript { .api }
164
type OnMount<Args extends unknown[], Result> = <S extends SetAtom<Args, Result>>(
165
setAtom: S
166
) => OnUnmount | void;
167
168
type OnUnmount = () => void;
169
```
170
171
### SetAtom Type
172
173
Type for atom setter functions.
174
175
```typescript { .api }
176
type SetAtom<Args extends unknown[], Result> = <A extends Args>(
177
...args: A
178
) => Result;
179
```
180
181
## Utility Types
182
183
### Getter and Setter Types
184
185
Core function types for atom operations.
186
187
```typescript { .api }
188
type Getter = <Value>(atom: Atom<Value>) => Value;
189
190
type Setter = <Value, Args extends unknown[], Result>(
191
atom: WritableAtom<Value, Args, Result>,
192
...args: Args
193
) => Result;
194
```
195
196
### SetStateAction Type
197
198
Type for state update actions, supporting both direct values and updater functions.
199
200
```typescript { .api }
201
type SetStateAction<Value> = Value | ((prev: Value) => Value);
202
```
203
204
### Store Interface
205
206
Interface for atom stores that manage atom values and subscriptions.
207
208
```typescript { .api }
209
interface Store {
210
/** Get the current value of an atom */
211
get: <Value>(atom: Atom<Value>) => Value;
212
/** Set the value of a writable atom */
213
set: <Value, Args extends unknown[], Result>(
214
atom: WritableAtom<Value, Args, Result>,
215
...args: Args
216
) => Result;
217
/** Subscribe to atom changes */
218
sub: (atom: AnyAtom, listener: Listener) => Unsubscribe;
219
}
220
221
type AnyAtom = Atom<unknown>;
222
type Listener = () => void;
223
type Unsubscribe = () => void;
224
```
225
226
## Store Management
227
228
### Store Creation
229
230
Functions for creating and managing atom stores.
231
232
```typescript { .api }
233
/**
234
* Create a new isolated atom store
235
* @returns New Store instance
236
*/
237
function createStore(): Store;
238
239
/**
240
* Get the default global store, creating one if it doesn't exist
241
* @returns The default Store instance
242
*/
243
function getDefaultStore(): Store;
244
245
/**
246
* Internal function to override the default store creation behavior
247
* @param fn - Function that returns a new createStore function
248
*/
249
function INTERNAL_overrideCreateStore(
250
fn: (prev: typeof createStore | undefined) => typeof createStore
251
): void;
252
```
253
254
**Usage Examples:**
255
256
```typescript
257
import { createStore, getDefaultStore } from "jotai";
258
259
// Create a custom store
260
const myStore = createStore();
261
262
// Get the default store
263
const defaultStore = getDefaultStore();
264
265
// Use custom store
266
const value = myStore.get(countAtom);
267
myStore.set(countAtom, 10);
268
```
269
270
## Type Extraction Utilities
271
272
Utility types for extracting information from atom types.
273
274
```typescript { .api }
275
/**
276
* Extract the value type from an atom type
277
*/
278
type ExtractAtomValue<AtomType> = AtomType extends Atom<infer Value> ? Value : never;
279
280
/**
281
* Extract the argument types from a writable atom type
282
*/
283
type ExtractAtomArgs<AtomType> = AtomType extends WritableAtom<any, infer Args, any> ? Args : never;
284
285
/**
286
* Extract the result type from a writable atom type
287
*/
288
type ExtractAtomResult<AtomType> = AtomType extends WritableAtom<any, any, infer Result> ? Result : never;
289
```
290
291
**Usage Examples:**
292
293
```typescript
294
import type { ExtractAtomValue, ExtractAtomArgs } from "jotai";
295
296
const numberAtom = atom(42);
297
const incrementAtom = atom(null, (get, set, amount: number) => {
298
set(numberAtom, get(numberAtom) + amount);
299
});
300
301
// Extract types from atoms
302
type NumberValue = ExtractAtomValue<typeof numberAtom>; // number
303
type IncrementArgs = ExtractAtomArgs<typeof incrementAtom>; // [number]
304
```