Skip to content

Commit 4edd971

Browse files
icyJosephcassiozen
authored andcommitted
feat: Add use-constant for initialState and getReducer
1 parent 14a9d3b commit 4edd971

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@
5151
},
5252
"size-limit": [
5353
{
54-
"path": "dist/usemachine.cjs.production.min.js",
54+
"path": "dist/usestatemachine.cjs.production.min.js",
5555
"limit": "512 B"
5656
},
5757
{
58-
"path": "dist/usemachine.esm.js",
58+
"path": "dist/usestatemachine.esm.js",
5959
"limit": "512 B"
6060
}
6161
]

src/index.tsx

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useReducer, Dispatch } from 'react';
1+
import { useEffect, useReducer, Dispatch, useRef } from 'react';
22

33
type Transition =
44
| string
@@ -84,19 +84,28 @@ const getReducer = <
8484
};
8585
};
8686

87+
const useConstant = <T,>(init: () => T) => {
88+
const ref = useRef<T | null>(null);
89+
90+
if (ref.current === null) {
91+
ref.current = init();
92+
}
93+
return ref.current;
94+
};
95+
8796
export default function useStateMachine<Context extends Record<PropertyKey, any>>(context?: Context) {
8897
return function useStateMachineWithContext<Config extends MachineConfig<Context>>(config: Config) {
8998
type IndexableState = keyof typeof config.states;
9099
type State = keyof Config['states'];
91100
type Event = KeysOfTransition<TransitionEvent<Config['states']>>;
92101

93-
const initialState = {
102+
const initialState = useConstant(() => ({
94103
value: config.initial as State,
95104
context: context ?? ({} as Context),
96105
nextEvents: Object.keys(config.states[config.initial].on ?? []) as Event[],
97-
};
106+
}));
98107

99-
const reducer = getReducer<Context, Config, State, Event>(config);
108+
const reducer = useConstant(() => getReducer<Context, Config, State, Event>(config));
100109

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

0 commit comments

Comments
 (0)