Closed ofhouse closed 2 years ago
I am attentive to your PR, something interesting that I found in this was an error in React within Codesandbox, I think this only happens in Codesandbox, I have not verified in other environments
https://codesandbox.io/s/currying-pond-1n5dce?file=/src/App.js
the React version of Codesandbox, the init function is executed 2 times 🤔
Hi, thanks for reviewing it. Nice catch, I think this is a normal behaviour of react when it uses the development build, as stated here: https://github.com/facebook/react/issues/16295#issuecomment-610098654
There is no "problem". React intentionally calls your reducer twice to make any unexpected side effects more apparent. Since your reducer is pure, calling it twice doesn't affect the logic of your application. So you shouldn't worry about this.
In production, it will only be called once.
I checked it out locally and created a production build from it and then the init function is only called once instead of twice from the development build.
I have generated some changes to the PR, I will wait for your Review before generating the Merge
Ready merged 🎉, Thanks for your PR, I will be attentive to what you need
To ensure a better compatibility with React based reducers, this adds an optional third argument to the
useReducer
hook to lazy initialize the state in the same way as React does it:Implementation follows the same way as react does it:
https://github.com/facebook/react/blob/ce13860281f833de8a3296b7a3dad9caced102e9/packages/react-reconciler/src/ReactFiberHooks.new.js#L732-L737
Changes
init
argument touseReducer
useReducer