Skip to content

Commit

Permalink
feat: Add use-constant for initialState and getReducer
Browse files Browse the repository at this point in the history
  • Loading branch information
icyJoseph authored and cassiozen committed Apr 30, 2021
1 parent 14a9d3b commit 4edd971
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
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

0 comments on commit 4edd971

Please # to comment.