the-road-to-learn-react/react-usereducer-middleware

Afterware function runs twice

suneg opened this issue · 2 comments

suneg commented

I've use this handy little utility on a project, but I've come across an issue where the afterware functions are called twice.

Repro steps

  1. Add the following code in the App function:
  const [test, setTest] = React.useState('test')

  React.useEffect(() => {
    console.log('todos changed')
    setTest(new Date())
  },[todos])
  1. Run the app (npm start) and bring up the dev tools console
  2. Click one of the check-boxes

Expected result:

logger before:
logger after:
todos changed

Actual result:

logger before:
logger after:
todos changed
logger after:

Screenshot from 2021-03-22 19-19-16

I'm unsure about the reason for it, but I've boiled it down to setting component state to an updated value, from an effect that relies on the state from the reducer. Clearly it does not make logical sense that the afterware would run more than once, or any other count than the middleware for that matter.

Can you check whether this change helps? I noticed this in my application as well, but forgot to update this repo here.

39dd042

suneg commented

That seems to do the trick. I was experimenting with

}, [afterwareFns.length, state]);

instead of

}, [afterwareFns, state]);

Which also seems to work. But that might have some undesired side-effects.