Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(react): optimize react layer #5000

Merged
merged 6 commits into from
Jul 30, 2024
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
9 changes: 9 additions & 0 deletions .changeset/early-spies-beg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@xstate/store': patch
---

- replace use-sync-external-store/shim with useSyncExternalStore from react
- do not memoize getSnapshot in uSES
- implement getServerSnapshot in uSES
- expect store to always be defined
- update react types to v18 and testing library to v16
16 changes: 5 additions & 11 deletions packages/core/src/stateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,9 @@ function getValueFromAdj(baseNode: AnyStateNode, adjList: AdjList): StateValue {
return stateValue;
}

function getAdjList<
TContext extends MachineContext,
TE extends EventObject
>(stateNodes: StateNodeIterable<TContext, TE>): AdjList {
function getAdjList<TContext extends MachineContext, TE extends EventObject>(
stateNodes: StateNodeIterable<TContext, TE>
): AdjList {
const adjList: AdjList = new Map();

for (const s of stateNodes) {
Expand Down Expand Up @@ -528,9 +527,7 @@ function isHistoryNode(
return stateNode.type === 'history';
}

function getInitialStateNodesWithTheirAncestors(
stateNode: AnyStateNode
) {
function getInitialStateNodesWithTheirAncestors(stateNode: AnyStateNode) {
const states = getInitialStateNodes(stateNode);
for (const initialState of states) {
for (const ancestor of getProperAncestors(initialState, stateNode)) {
Expand Down Expand Up @@ -562,10 +559,7 @@ export function getInitialStateNodes(stateNode: AnyStateNode) {
return set;
}
/** Returns the child state node from its relative `stateKey`, or throws. */
function getStateNode(
stateNode: AnyStateNode,
stateKey: string
): AnyStateNode {
function getStateNode(stateNode: AnyStateNode, stateKey: string): AnyStateNode {
if (isStateId(stateKey)) {
return stateNode.machine.getStateNodeById(stateKey);
}
Expand Down
6 changes: 3 additions & 3 deletions packages/xstate-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@
"use-sync-external-store": "^1.2.0"
},
"devDependencies": {
"@testing-library/react": "^14.2.1",
"@types/react": "^17.0.43",
"@types/react-dom": "^17.0.14",
"@testing-library/react": "^16.0.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/use-sync-external-store": "^0.0.3",
"react": "^18.0.0",
"react-dom": "^18.0.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/xstate-react/src/useActor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function useActor<TLogic extends AnyActorLogic>(
}, [actorRef]);

const subscribe = useCallback(
(handleStoreChange) => {
(handleStoreChange: () => void) => {
const { unsubscribe } = actorRef.subscribe(handleStoreChange);
return unsubscribe;
},
Expand Down
8 changes: 4 additions & 4 deletions packages/xstate-react/test/createActorContext.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('createActorContext', () => {
const SomeContext = createActorContext(someMachine);

const Component = () => {
const value = SomeContext.useSelector((state) => state.value);
const value = SomeContext.useSelector((state) => state.value as string);

return <div data-testid="value">{value}</div>;
};
Expand Down Expand Up @@ -76,7 +76,7 @@ describe('createActorContext', () => {

return (
<>
<div data-testid="value">{state.value}</div>
<div data-testid="value">{state.value as string}</div>
<button
data-testid="next"
onClick={() => actorRef.send({ type: 'NEXT' })}
Expand Down Expand Up @@ -196,7 +196,7 @@ describe('createActorContext', () => {
const actor = SomeContext.useActorRef();
const value = useSelector(actor, (state) => state.value);

return <div data-testid="value">{value}</div>;
return <div data-testid="value">{value as string}</div>;
};

const App = () => {
Expand Down Expand Up @@ -412,7 +412,7 @@ describe('createActorContext', () => {
actorRef.send({ type: 'next' });
}}
>
{state.value}
{state.value as string}
</div>
);
};
Expand Down
4 changes: 2 additions & 2 deletions packages/xstate-react/test/useActor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ describeEachReactMode('useActor (%s)', ({ suiteKey, render }) => {
const [state, send] = useActor(machine);
return (
<>
<div data-testid="result">{state.value}</div>
<div data-testid="result">{state.value as string}</div>
<button onClick={() => send({ type: 'EV' })} />
</>
);
Expand Down Expand Up @@ -740,7 +740,7 @@ describeEachReactMode('useActor (%s)', ({ suiteKey, render }) => {
);
return (
<>
<div data-testid="result">{state.value}</div>
<div data-testid="result">{state.value as string}</div>
<button onClick={() => send({ type: 'EV' })} />
</>
);
Expand Down
10 changes: 5 additions & 5 deletions packages/xstate-react/test/useActorRef.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ describeEachReactMode('useActorRef (%s)', ({ suiteKey, render }) => {
>
Send to child
</button>
<div data-testid="child-state">{childState.value}</div>
<div data-testid="child-state">{childState.value as string}</div>
</>
);
};
Expand Down Expand Up @@ -251,7 +251,7 @@ describeEachReactMode('useActorRef (%s)', ({ suiteKey, render }) => {
>
Send to child
</button>
<div data-testid="child-state">{childState.value}</div>
<div data-testid="child-state">{childState.value as string}</div>
</>
);
};
Expand Down Expand Up @@ -325,7 +325,7 @@ describeEachReactMode('useActorRef (%s)', ({ suiteKey, render }) => {

it('should work with a promise actor', async () => {
const promiseLogic = fromPromise(
() => new Promise((resolve) => setTimeout(() => resolve(42), 10))
() => new Promise<number>((resolve) => setTimeout(() => resolve(42), 10))
);

const App = () => {
Expand Down Expand Up @@ -506,7 +506,7 @@ describeEachReactMode('useActorRef (%s)', ({ suiteKey, render }) => {
>
Send event
</button>
<span>{value}</span>
<span>{value as string}</span>
</>
);
}
Expand Down Expand Up @@ -565,7 +565,7 @@ describeEachReactMode('useActorRef (%s)', ({ suiteKey, render }) => {
>
Send event
</button>
<span>{value}</span>
<span>{value as string}</span>
</>
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/xstate-react/test/useSelector.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ describeEachReactMode('useSelector (%s)', ({ suiteKey, render }) => {

return (
<>
<div data-testid="child-state">{childState.value}</div>
<div data-testid="child-state">{childState.value as string}</div>
<button
data-testid="child-send"
onClick={() => childRef.send({ type: 'NEXT' })}
Expand Down
6 changes: 2 additions & 4 deletions packages/xstate-store/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,9 @@
"bugs": {
"url": "https://github.com/statelyai/xstate/issues"
},
"dependencies": {
"use-sync-external-store": "^1.2.0"
},
"devDependencies": {
"@testing-library/react": "^14.2.1",
"@testing-library/react": "^16.0.0",
"@types/react": "^18.3.3",
"@xstate/react": "^4.1.1",
"@xstate/vue": "^3.1.2",
"immer": "^10.0.2",
Expand Down
65 changes: 30 additions & 35 deletions packages/xstate-store/src/react.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import { useCallback } from 'react';
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';
import { useCallback, useRef, useSyncExternalStore } from 'react';
import { Store, SnapshotFromStore } from './types';

type SyncExternalStoreSubscribe = Parameters<
typeof useSyncExternalStoreWithSelector
>[0];

function defaultCompare<T>(a: T, b: T) {
function defaultCompare<T>(a: T | undefined, b: T) {
return a === b;
}

function useSelectorWithCompare<TStore extends Store<any, any>, T>(
selector: (snapshot: SnapshotFromStore<TStore>) => T,
compare: (a: T | undefined, b: T) => boolean
): (snapshot: SnapshotFromStore<TStore>) => T {
const previous = useRef<T>();

return (state) => {
const next = selector(state);
return compare(previous.current, next)
? (previous.current as T)
: (previous.current = next);
};
}

/**
* A React hook that subscribes to the `store` and selects a value from the
* store's snapshot, with an optional compare function.
Expand All @@ -31,36 +40,22 @@ function defaultCompare<T>(a: T, b: T) {
* previous value
* @returns The selected value
*/
export function useSelector<TStore extends Store<any, any> | undefined, T>(
export function useSelector<TStore extends Store<any, any>, T>(
store: TStore,
selector: (
snapshot: TStore extends Store<any, any>
? SnapshotFromStore<TStore>
: undefined
) => T,
compare: (a: T, b: T) => boolean = defaultCompare
selector: (snapshot: SnapshotFromStore<TStore>) => T,
compare: (a: T | undefined, b: T) => boolean = defaultCompare
): T {
const subscribe: SyncExternalStoreSubscribe = useCallback(
(handleStoreChange) => {
if (!store) {
return () => {};
}
const { unsubscribe } = store.subscribe(handleStoreChange);
return unsubscribe;
},
[store]
);

const boundGetSnapshot = useCallback(() => store?.getSnapshot(), [store]);
const selectorWithCompare = useSelectorWithCompare(selector, compare);

const selectedSnapshot = useSyncExternalStoreWithSelector(
subscribe,
// @ts-ignore
boundGetSnapshot,
boundGetSnapshot,
selector,
compare
return useSyncExternalStore(
useCallback(
(handleStoreChange) => store.subscribe(handleStoreChange).unsubscribe,
[store]
),
() => selectorWithCompare(store.getSnapshot() as SnapshotFromStore<TStore>),
() =>
selectorWithCompare(
store.getInitialSnapshot() as SnapshotFromStore<TStore>
)
);

return selectedSnapshot;
}
Loading
Loading