Skip to content
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

feat(utils): atomWithLazy for lazily initialized primitive atoms. #2465

Merged
merged 10 commits into from
Apr 4, 2024
96 changes: 96 additions & 0 deletions docs/utilities/lazy.mdx
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
```
1 change: 1 addition & 0 deletions src/vanilla/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ export { atomWithObservable } from './utils/atomWithObservable.ts'
export { loadable } from './utils/loadable.ts'
export { unwrap } from './utils/unwrap.ts'
export { atomWithRefresh } from './utils/atomWithRefresh.ts'
export { atomWithLazy } from './utils/atomWithLazy.ts'
20 changes: 20 additions & 0 deletions src/vanilla/utils/atomWithLazy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { atom } from '../../vanilla.ts'
import type { Atom, PrimitiveAtom, SetStateAction } from '../../vanilla.ts'

export function atomWithLazy<Value>(makeInitial: () => Value) {
const wrappedAtom: Atom<PrimitiveAtom<Value>> & { init?: Atom<undefined> } =
atom(() => atom(makeInitial()))

const proxyAtom = atom(
(get) => get(get(wrappedAtom)),
(get, set, value: SetStateAction<Value>) => set(get(wrappedAtom), value),
)

wrappedAtom.init = atom(undefined)
// when writing to wrappedAtom through proxyAtom, the store
// thinks we are actually storing the value of `proxyAtom`.
wrappedAtom.unstable_is = (a) =>
a.unstable_is ? a.unstable_is(proxyAtom) : a === proxyAtom
iwoplaza marked this conversation as resolved.
Show resolved Hide resolved

return proxyAtom
}
41 changes: 41 additions & 0 deletions tests/vanilla/utils/atomWithLazy.test.ts
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)
})
Loading