MCPcopy
hub / github.com/statelyai/xstate / useActor

Function useActor

packages/xstate-react/src/useActor.ts:17–79  ·  view source on GitHub ↗
(
  logic: TLogic,
  ...[options]: ConditionalRequired<
    [
      options?: ActorOptions<TLogic> & {
        [K in RequiredActorOptionsKeys<TLogic>]: unknown;
      }
    ],
    IsNotNever<RequiredActorOptionsKeys<TLogic>>
  >
)

Source from the content-addressed store, hash-verified

15import { useIdleActorRef } from './useActorRef.ts';
16
17export function useActor<TLogic extends AnyActorLogic>(
18 logic: TLogic,
19 ...[options]: ConditionalRequired<
20 [
21 options?: ActorOptions<TLogic> & {
22 [K in RequiredActorOptionsKeys<TLogic>]: unknown;
23 }
24 ],
25 IsNotNever<RequiredActorOptionsKeys<TLogic>>
26 >
27): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>] {
28 if (
29 isDevelopment &&
30 !!logic &&
31 'send' in logic &&
32 typeof logic.send === 'function'
33 ) {
34 throw new Error(
35 `useActor() expects actor logic (e.g. a machine), but received an ActorRef. Use the useSelector(actorRef, ...) hook instead to read the ActorRef's snapshot.`
36 );
37 }
38
39 const actorRef = useIdleActorRef(logic, options);
40
41 const getSnapshot = useCallback(() => {
42 return actorRef.getSnapshot();
43 }, [actorRef]);
44
45 const subscribe = useCallback(
46 (handleStoreChange: () => void) => {
47 const { unsubscribe } = actorRef.subscribe({
48 next: handleStoreChange,
49 error: handleStoreChange
50 });
51 return unsubscribe;
52 },
53 [actorRef]
54 );
55
56 const actorSnapshot = useSyncExternalStore(
57 subscribe,
58 getSnapshot,
59 getSnapshot
60 );
61
62 const snapshotWithStatus =
63 'status' in actorSnapshot
64 ? (actorSnapshot as Snapshot<unknown>)
65 : undefined;
66 if (snapshotWithStatus?.status === 'error') {
67 throw snapshotWithStatus.error;
68 }
69
70 useEffect(() => {
71 actorRef.start();
72
73 return () => {
74 stopRootWithRehydration(actorRef);

Callers 9

ComponentFunction · 0.90
FetcherFunction · 0.90
TestFunction · 0.90
SpawnerFunction · 0.90
ComponentFunction · 0.90
ToggleFunction · 0.90
AppFunction · 0.90
useMachineFunction · 0.90
AppFunction · 0.90

Calls 6

useIdleActorRefFunction · 0.90
stopRootWithRehydrationFunction · 0.90
useSyncExternalStoreFunction · 0.85
getSnapshotMethod · 0.80
subscribeMethod · 0.65
startMethod · 0.65

Tested by 7

ComponentFunction · 0.72
FetcherFunction · 0.72
TestFunction · 0.72
SpawnerFunction · 0.72
ComponentFunction · 0.72
ToggleFunction · 0.72
AppFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…