-
-
Notifications
You must be signed in to change notification settings - Fork 661
feat(utils): atomWithLazy for lazily initialized primitive atoms. #2465
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b529289
feat(utils): atomWithLazy for lazily initialized primitive atoms.
iwoplaza 8504553
tweak test for older ts versions
iwoplaza 193bc1f
add `unstable_is` hack for use in `jotai-store`
iwoplaza 94c47dc
add documentation for atomWithLazy
iwoplaza 2396718
update lazy docs
iwoplaza 90bc12d
remove semicolons in lazy docs
iwoplaza 23d1ec6
Merge branch 'main' into feat/utils/lazy-initialization
dai-shi 240b13d
add more elegant implementation for atomWithLazy
iwoplaza 0249b0e
clear type declarations
iwoplaza 72f8320
Merge branch 'main' into feat/utils/lazy-initialization
dai-shi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
--- | ||
title: Lazy | ||
nav: 3.03 | ||
keywords: lazy,initialize,init,loading | ||
--- | ||
|
||
When defining primitive atoms, their initial value has to be bound at definition time. | ||
If creating that initial value is computationally expensive, or the value is not accessible during definition, | ||
it would be best to postpone the atom's initialization until its [first use in the store](#using-multiple-stores). | ||
|
||
```jsx | ||
const imageDataAtom = atom(initializeExpensiveImage()) // 1) has to be computed here | ||
|
||
function Home() { | ||
... | ||
} | ||
|
||
function ImageEditor() { | ||
// 2) used only in this route | ||
const [imageData, setImageData] = useAtom(imageDataAtom); | ||
... | ||
} | ||
|
||
function App() { | ||
return ( | ||
<Router> | ||
<Route path="/" component={Home} /> | ||
<Route path="/edit" component={ImageEditor} /> | ||
</Router> | ||
) | ||
} | ||
``` | ||
|
||
## atomWithLazy | ||
|
||
Ref: https://github.com/pmndrs/jotai/pull/2465 | ||
|
||
We can use `atomWithLazy` to create a primitive atom whose initial value will be computed at [first use in the store](#using-multiple-stores). | ||
After initialization, it will behave like a regular primitive atom (can be written to). | ||
|
||
### Usage | ||
|
||
```jsx | ||
import { atomWithLazy } from 'jotai/utils' | ||
|
||
// passing the initialization function | ||
const imageDataAtom = atomWithLazy(initializeExpensiveImage) | ||
|
||
function Home() { | ||
... | ||
} | ||
|
||
function ImageEditor() { | ||
// only gets initialized if user goes to `/edit`. | ||
const [imageData, setImageData] = useAtom(imageDataAtom); | ||
... | ||
} | ||
|
||
function App() { | ||
return ( | ||
<Router> | ||
<Route path="/" component={Home} /> | ||
<Route path="/edit" component={ImageEditor} /> | ||
</Router> | ||
) | ||
} | ||
``` | ||
|
||
### Using multiple stores | ||
|
||
Since each store is its separate universe, the initial value will be recreated exactly once per store (unless using something like `jotai-scope`, which fractures a store into smaller universes). | ||
|
||
```ts | ||
type RGB = [number, number, number]; | ||
|
||
function randomRGB(): RGB { | ||
... | ||
} | ||
|
||
const lift = (value: number) => ([r, g, b]: RGB) => { | ||
return [r + value, g + value, b + value] | ||
} | ||
|
||
const colorAtom = lazyAtom(randomRGB) | ||
|
||
let store = createStore() | ||
|
||
console.log(store.get(colorAtom)) // [0, 36, 128] | ||
store.set(colorAtom, lift(8)) | ||
console.log(store.get(colorAtom)) // [8, 44, 136] | ||
|
||
// recreating store, sometimes done when logging out or resetting the app in some way | ||
store = createStore() | ||
|
||
console.log(store.get(colorAtom)) // [255, 12, 46] -- a new random color | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { PrimitiveAtom, atom } from '../../vanilla.ts' | ||
|
||
export function atomWithLazy<Value>( | ||
makeInitial: () => Value, | ||
): PrimitiveAtom<Value> { | ||
return { | ||
...atom(undefined as unknown as Value), | ||
get init() { | ||
return makeInitial() | ||
}, | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import { expect, it, vi } from 'vitest' | ||
import { createStore } from 'jotai/vanilla' | ||
import { atomWithLazy } from 'jotai/vanilla/utils' | ||
|
||
it('initializes on first store get', async () => { | ||
const storeA = createStore() | ||
const storeB = createStore() | ||
|
||
let externalState = 'first' | ||
const initializer = vi.fn(() => externalState) | ||
const anAtom = atomWithLazy(initializer) | ||
|
||
expect(initializer).not.toHaveBeenCalled() | ||
expect(storeA.get(anAtom)).toEqual('first') | ||
expect(initializer).toHaveBeenCalledOnce() | ||
|
||
externalState = 'second' | ||
|
||
expect(storeA.get(anAtom)).toEqual('first') | ||
expect(initializer).toHaveBeenCalledOnce() | ||
expect(storeB.get(anAtom)).toEqual('second') | ||
expect(initializer).toHaveBeenCalledTimes(2) | ||
}) | ||
|
||
it('is writable', async () => { | ||
const store = createStore() | ||
const anAtom = atomWithLazy(() => 0) | ||
|
||
store.set(anAtom, 123) | ||
|
||
expect(store.get(anAtom)).toEqual(123) | ||
}) | ||
|
||
it('should work with a set state action', async () => { | ||
const store = createStore() | ||
const anAtom = atomWithLazy(() => 4) | ||
|
||
store.set(anAtom, (prev: number) => prev * prev) | ||
|
||
expect(store.get(anAtom)).toEqual(16) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should this function be called only once crossing the store?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, it should.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, it should call once for each store.
#2458 (comment)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, I thought that is what they meant. Once per each store is right.