Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,7 @@
"immer": "^9.0.21",
"redux": "^5.0.1",
"redux-thunk": "^3.1.0",
"ts-toolbelt": "^9.6.0",
"use-sync-external-store": "^1.4.0"
"ts-toolbelt": "^9.6.0"
},
"devDependencies": {
"@babel/core": "^7.22.9",
Expand Down
17 changes: 15 additions & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@ const external = (id) => !id.startsWith('.') && !id.startsWith(root);

const extensions = ['.js'];

const useClientBanner = `'use client';`;

function createESMConfig(input, output) {
return {
input,
output: { sourcemap: true, file: output, format: 'esm' },
output: {
sourcemap: true,
file: output,
format: 'esm',
banner: useClientBanner,
},
external,
plugins: [
resolve({ extensions }),
Expand All @@ -28,7 +35,13 @@ function createESMConfig(input, output) {
function createCommonJSConfig(input, output) {
return {
input,
output: { sourcemap: true, file: output, format: 'cjs', exports: 'named' },
output: {
sourcemap: true,
file: output,
format: 'cjs',
exports: 'named',
banner: useClientBanner,
},
external,
plugins: [
resolve({ extensions }),
Expand Down
109 changes: 90 additions & 19 deletions src/hooks.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,96 @@
import { useContext, useDebugValue, useEffect, useState } from 'react';
import {
useContext,
useDebugValue,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from 'react';
import EasyPeasyContext from './context';

const useNotInitialized = () => {
throw new Error('uSES not initialized!');
};
let useSyncExternalStoreWithSelector = useNotInitialized;
export const initializeUseStoreState = (fn) => {
useSyncExternalStoreWithSelector = fn;
};

const refEquality = (a, b) => a === b;

function useSyncExternalStoreWithSelector(
subscribe,
getSnapshot,
getServerSnapshot,
selector,
isEqual,
) {
const instRef = useRef(null);
let inst;
if (instRef.current === null) {
inst = { hasValue: false, value: null };
instRef.current = inst;
} else {
inst = instRef.current;
}

const [getSelection, getServerSelection] = useMemo(() => {
let hasMemo = false;
let memoizedSnapshot;
let memoizedSelection;
const memoizedSelector = (nextSnapshot) => {
if (!hasMemo) {
hasMemo = true;
memoizedSnapshot = nextSnapshot;
const nextSelection = selector(nextSnapshot);
if (isEqual !== undefined && inst.hasValue) {
const currentSelection = inst.value;
if (isEqual(currentSelection, nextSelection)) {
memoizedSelection = currentSelection;
return currentSelection;
}
}
memoizedSelection = nextSelection;
return nextSelection;
}

const prevSnapshot = memoizedSnapshot;
const prevSelection = memoizedSelection;

if (Object.is(prevSnapshot, nextSnapshot)) {
return prevSelection;
}

const nextSelection = selector(nextSnapshot);

if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
memoizedSnapshot = nextSnapshot;
return prevSelection;
}

memoizedSnapshot = nextSnapshot;
memoizedSelection = nextSelection;
return nextSelection;
};

const getSnapshotWithSelector = () => memoizedSelector(getSnapshot());
const getServerSnapshotWithSelector =
getServerSnapshot == null
? undefined
: () => memoizedSelector(getServerSnapshot());

return [getSnapshotWithSelector, getServerSnapshotWithSelector];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [getSnapshot, getServerSnapshot, selector, isEqual]);

const value = useSyncExternalStore(
subscribe,
getSelection,
getServerSelection,
);

useEffect(() => {
inst.hasValue = true;
inst.value = value;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);

return value;
}

export function createStoreStateHook(Context) {
return function useStoreState(mapState, equalityFn = refEquality) {
if (process.env.NODE_ENV !== 'production') {
Expand All @@ -31,19 +111,10 @@

const store = useContext(Context);

/*
function useSyncExternalStoreWithSelector<Snapshot, Selection>(
subscribe: (onStoreChange: () => void) => () => void,
getSnapshot: () => Snapshot,
getServerSnapshot: undefined | null | (() => Snapshot),
selector: (snapshot: Snapshot) => Selection,
isEqual?: (a: Selection, b: Selection) => boolean,
): Selection;
*/
const selectedState = useSyncExternalStoreWithSelector(
store.subscribe,
store.getState,
store.getState, // getServerSnapshot = getState
store.getState,
mapState,
equalityFn,
);
Expand Down Expand Up @@ -84,7 +155,7 @@
const [rehydrated, setRehydrated] = useState(false);
useEffect(() => {
store.persist.resolveRehydration().then(() => setRehydrated(true));
}, []);

Check warning on line 158 in src/hooks.js

View workflow job for this annotation

GitHub Actions / Code Quality (lint)

React Hook useEffect has a missing dependency: 'store.persist'. Either include it or remove the dependency array
return rehydrated;
};
}
Expand Down
10 changes: 0 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
// React 18 requires the use of the useSyncExternalStore hook for external
// stores to hook into its concurrent features. We want to continue supporting
// older versions of React (16/17), so we are utilsing a shim provided by the
// React team which will ensure backwards compatibility;
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';

import { initializeUseStoreState } from './hooks';

initializeUseStoreState(useSyncExternalStoreWithSelector);

export * from './hooks';
export * from './create-store';
export * from './create-context-store';
Expand Down
18 changes: 6 additions & 12 deletions src/use-local-store.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useRef, useSyncExternalStore } from 'react';
import { useMemoOne } from './lib';
import { createStore } from './create-store';

Expand All @@ -24,17 +24,11 @@ export function useLocalStore(
return _store;
}, dependencies);

const [currentState, setCurrentState] = useState(() => store.getState());

useEffect(() => {
setCurrentState(store.getState());
return store.subscribe(() => {
const nextState = store.getState();
if (currentState !== nextState) {
setCurrentState(nextState);
}
});
}, [store]);
const currentState = useSyncExternalStore(
store.subscribe,
store.getState,
store.getState,
);

return [currentState, store.getActions(), store];
}
Loading