diff --git a/package.json b/package.json index 9664bf0..ad20fb0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "delta-state", - "version": "1.1.5", + "version": "1.1.6", "description": "A modern version of the Delta state manager - written for TS and with the use of React Hooks.", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/react.ts b/src/react.ts index 6a8c586..de8bf75 100644 --- a/src/react.ts +++ b/src/react.ts @@ -42,35 +42,44 @@ const createImpl = >(store: Store, init: T) => { export const useAtom = ( atom: T, update: (set: (next: T) => T) => (next: T) => T | Promise, - link?: (source: T, local: T) => T, + link?: (source: T, local: T) => T ) => { - const atomStore = useRef(new Atom(atom)).current; - const lastLinkedState = useRef(atom); + const atomStore = useRef( + new Atom(atom) + ).current; - const set = (next: T) => { - atomStore.value = next; - atomStore.subscribers.forEach((callback) => callback()); - return next; - }; + const lastLinkedState = useRef(atom) + + + const set = (next :T) => { + atomStore.value = next + atomStore.subscribers.forEach((callback) => callback()) + return next + } - const setUpdate = update(set); + const setUpdate = update(set) useMemo(() => { - if (lastLinkedState.current !== atom && link) { - lastLinkedState.current = atom; - atomStore.value = link(lastLinkedState.current, atomStore.value); + if (lastLinkedState.current !== atom && link){ + lastLinkedState.current = atom + atomStore.value = link(lastLinkedState.current, atomStore.value) } + }, [atom, atomStore, link]); + return [ useSyncExternalStore( (callback) => atomStore.subscribe(callback), () => atomStore.getState(), () => atomStore.getState(), ), - setUpdate, - ] as [T, typeof setUpdate]; + setUpdate + ] as [ + T, + typeof setUpdate + ] }; const createAtomImpl = (