Skip to content

Commit

Permalink
Avoid using svelte/store's get in useSelector (#3603)
Browse files Browse the repository at this point in the history
* Avoid using svelte store get in useSelector.

* Add changeset.

* Reorder assigning the local variable and calling `set` with that value

* Tweak changeset

Co-authored-by: Mateusz Burzyński <[email protected]>
  • Loading branch information
mittinatten and Andarist authored Nov 14, 2022
1 parent 5e0808e commit 44719c2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/afraid-kids-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@xstate/svelte': patch
---

Improve performance of the `useSelector` by avoiding `get`
10 changes: 7 additions & 3 deletions packages/xstate-svelte/src/useSelector.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { get, readable } from 'svelte/store';
import { readable } from 'svelte/store';
import type { ActorRef, Subscribable, Subscription } from 'xstate';

const defaultCompare = (a, b) => a === b;
Expand All @@ -13,10 +13,14 @@ export const useSelector = <
compare: (a: T, b: T) => boolean = defaultCompare
) => {
let sub: Subscription;
const selected = readable(selector(actor.getSnapshot()), (set) => {

let prevSelected = selector(actor.getSnapshot());

const selected = readable(prevSelected, (set) => {
sub = actor.subscribe((state) => {
const nextSelected = selector(state);
if (!compare(get(selected), nextSelected)) {
if (!compare(prevSelected, nextSelected)) {
prevSelected = nextSelected;
set(nextSelected);
}
});
Expand Down

0 comments on commit 44719c2

Please sign in to comment.