cassiozen / useStateMachine

The <1 kb state machine hook for React
MIT License
2.38k stars 47 forks source link

Question about useConstant #55

Closed burtek closed 3 years ago

burtek commented 3 years ago

https://github.com/cassiozen/useStateMachine/blob/85d373eeb6c30e1e17c2fc58711ede605f830a0b/src/index.tsx#L197-L204

https://github.com/cassiozen/useStateMachine/blob/85d373eeb6c30e1e17c2fc58711ede605f830a0b/src/index.tsx#L218-L220

How is useConstant here better/different from react's useMemo? It looks like it should work same as

const reducer = useMemo(() => getReducer<Context, Events, State, EventString>(config), []);
devanshj commented 3 years ago

Because useMemo doesn't guarantee that the function would be run only once, from the docs...

useMemo lets you memoize an expensive calculation if the dependencies are the same. However, it only serves as a hint, and doesn’t guarantee the computation won’t re-run. But sometimes you need to be sure an object is only created once.

Perhaps you'd be interested in comparison with other ways to do this and similar discussion in the issue pages of useConstant's repo (though the implementation is slightly different than the one here)

burtek commented 3 years ago

that makes sense, thank you :)