Reputation: 8042
With regards to this question:
useReducer Action dispatched twice
I've adapted a small code snippet in codesandbox taken from Dan Abramov's blog right here.
Now my question is this:
If I type something in the input field in between the 5 seconds interval and then inspect the console output I observe that when dispatch fires the "supposedly" closed over value of step
is the newly updated value I just typed in the input field instead of 1
which was the case when useEffect was declared. Why is this the case?
Upvotes: 0
Views: 258
Reputation: 16309
Every time you change the value of your input you call setStep
which triggers a re-render of your Counter
component. This in turn leads to your reducer function being re-created with the updated value of step
being closed over.
Your effect does not close over the initial value of step
, just over dispatch
.
To observe the behaviour you expect you would have to wrap your reducer in a useCallback
without providing any dependencies. Then it wouldn't get recreated every time.
Upvotes: 1