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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@
},
"size-limit": [
{
"path": "dist/usemachine.cjs.production.min.js",
"path": "dist/usestatemachine.cjs.production.min.js",
"limit": "512 B"
},
{
"path": "dist/usemachine.esm.js",
"path": "dist/usestatemachine.esm.js",
"limit": "512 B"
}
]
Expand Down
17 changes: 13 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useReducer, Dispatch } from 'react';
import { useEffect, useReducer, Dispatch, useRef } from 'react';

type Transition =
| string
Expand Down Expand Up @@ -84,19 +84,28 @@ const getReducer = <
};
};

const useConstant = <T,>(init: () => T) => {
const ref = useRef<T | null>(null);

if (ref.current === null) {
ref.current = init();
}
return ref.current;
};

export default function useStateMachine<Context extends Record<PropertyKey, any>>(context?: Context) {
return function useStateMachineWithContext<Config extends MachineConfig<Context>>(config: Config) {
type IndexableState = keyof typeof config.states;
type State = keyof Config['states'];
type Event = KeysOfTransition<TransitionEvent<Config['states']>>;

const initialState = {
const initialState = useConstant(() => ({
value: config.initial as State,
context: context ?? ({} as Context),
nextEvents: Object.keys(config.states[config.initial].on ?? []) as Event[],
};
}));

const reducer = getReducer<Context, Config, State, Event>(config);
const reducer = useConstant(() => getReducer<Context, Config, State, Event>(config));

const [machine, send] = useReducer(reducer, initialState);

Expand Down