Skip to content
This repository has been archived by the owner on Apr 3, 2024. It is now read-only.

Non-memoized / ref'd reducer runs into double dispatch issue when used in custom hook #18

Open
chrisdhanaraj opened this issue Aug 18, 2020 · 3 comments · May be fixed by #19
Open

Non-memoized / ref'd reducer runs into double dispatch issue when used in custom hook #18

chrisdhanaraj opened this issue Aug 18, 2020 · 3 comments · May be fixed by #19

Comments

@chrisdhanaraj
Copy link

chrisdhanaraj commented Aug 18, 2020

Hello! First off, love this library so much, it's made my code so much more clean.

Simplified reproduction: https://codesandbox.io/s/red-https-bxpo0?file=/src/App.tsx

But anyways, I've run into this scenario recently and was able to resolve by resolving this locally - but, to be honest, I'm not really sure of the React internals enough to PR this + test. Anyways, the scenario

  1. I want to use useEffectReducer in my own hook and export out it's dispatch so that other components can programmatically send out events to the reducer.
  2. However, when I leverage the dispatch it emits events twice.
  3. To resolve, you can useMemo the wrappedReducer .
const memoReducer = useMemo(() => wrappedReducer, []);

const [[state, effectStateEntityTuples, entitiesToStop], dispatch] = useReducer(
    memoReducer,
    initialStateAndEffects
 );
@davidkpiano
Copy link
Owner

I'd appreciate a PR with this change!

Also, note that logging to console is itself an effect, so if you do:

function useMyHook() {
  const [state, dispatch] = useEffectReducer((state, action, exec) => {
    exec(() => console.log("action: ", action));

    return state;
  }, []);

  return {
    state,
    dispatch
  };
}

Then it will log correctly.

@chrisdhanaraj chrisdhanaraj linked a pull request Aug 19, 2020 that will close this issue
@chrisdhanaraj
Copy link
Author

Ah you're right! I'll open a PR with the proposed change, but let me know if you want a more exhaustive example

@chrisdhanaraj
Copy link
Author

Updated with a more complicated example! I think, maybe, some of this probably relates back to the usage of Maps in component state

https://codesandbox.io/s/red-https-bxpo0?file=/src/App.tsx

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants