diff --git a/.size-snapshot.json b/.size-snapshot.json index 1dbf62fe3c..4a3940c34d 100644 --- a/.size-snapshot.json +++ b/.size-snapshot.json @@ -39,9 +39,9 @@ "gzipped": 354 }, "index.js": { - "bundled": 3974, - "minified": 1304, - "gzipped": 642, + "bundled": 4173, + "minified": 1360, + "gzipped": 672, "treeshaked": { "rollup": { "code": 14, @@ -53,14 +53,14 @@ } }, "index.cjs.js": { - "bundled": 5287, - "minified": 2019, - "gzipped": 859 + "bundled": 5494, + "minified": 2072, + "gzipped": 886 }, "index.iife.js": { - "bundled": 5530, - "minified": 1695, - "gzipped": 763 + "bundled": 5747, + "minified": 1757, + "gzipped": 795 }, "shallow.js": { "bundled": 644, diff --git a/src/index.ts b/src/index.ts index 1d06935fa9..d4186f34ac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -41,8 +41,9 @@ export default function create( const equalityFnRef = useRef(equalityFn) const erroredRef = useRef(false) + const state = api.getState() if (currentSliceRef.current === undefined) { - currentSliceRef.current = selector(api.getState()) + currentSliceRef.current = selector(state) } let newStateSlice: StateSlice | undefined @@ -57,7 +58,7 @@ export default function create( erroredRef.current ) { // Using local variables to avoid mutations in the render phase. - newStateSlice = selector(api.getState()) + newStateSlice = selector(state) hasNewStateSlice = !equalityFn( currentSliceRef.current as StateSlice, newStateSlice @@ -74,7 +75,8 @@ export default function create( erroredRef.current = false }) - useIsoLayoutEffect(() => { + const stateBeforeSubscriptionRef = useRef(state) + useEffect(() => { const listener = () => { try { const nextStateSlice = selectorRef.current(api.getState()) @@ -93,6 +95,9 @@ export default function create( } } const unsubscribe = api.subscribe(listener) + if (api.getState() !== stateBeforeSubscriptionRef.current) { + listener() // state has changed before subscription + } return unsubscribe }, [])