Skip to content

Commit

Permalink
fix: cache snapshot & add option deps (#30)
Browse files Browse the repository at this point in the history
* fix: cache snapshot & add option `deps`

* Update size limit
  • Loading branch information
yuyi919 authored Sep 23, 2024
1 parent 8dfbfa3 commit ff27de9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
8 changes: 8 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Store, StoreValue } from 'nanostores'
import type { DependencyList } from 'react'

type StoreKeys<T> = T extends { setKey: (k: infer K, v: any) => unknown }
? K
Expand All @@ -9,6 +10,13 @@ export interface UseStoreOptions<SomeStore> {
* Will re-render components only on specific key changes.
*/
keys?: StoreKeys<SomeStore>[]
/**
* @default
* ```ts
* [store, options.keys]
* ```
*/
deps?: DependencyList
}

/**
Expand Down
23 changes: 15 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import { listenKeys } from 'nanostores'
import { useCallback, useSyncExternalStore } from 'react'
import { useCallback, useRef, useSyncExternalStore } from 'react'

export function useStore(store, { keys, deps = [store, keys] } = {}) {
let snapshotRef = useRef()
snapshotRef.current = store.get()

export function useStore(store, opts = {}) {
let subscribe = useCallback(
onChange =>
opts.keys
? listenKeys(store, opts.keys, onChange)
: store.listen(onChange),
[opts.keys, store]
keys?.length > 0
? listenKeys(store, keys, emit(snapshotRef, onChange))
: store.listen(emit(snapshotRef, onChange)),
deps
)

let get = store.get.bind(store)
let get = () => snapshotRef.current

return useSyncExternalStore(subscribe, get, get)
}

let emit = (snapshotRef, onChange) => value => {
snapshotRef.current = value
onChange()
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
"index.js": "{ useStore }",
"nanostores": "{ map, computed }"
},
"limit": "871 B"
"limit": "901 B"
}
]
}

0 comments on commit ff27de9

Please sign in to comment.