atomicojs / atomico

Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.
https://atomicojs.dev
MIT License
1.15k stars 43 forks source link

Add lazy initializer to useReducer hook #77

Closed ofhouse closed 2 years ago

ofhouse commented 2 years ago

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:

const [state, dispatch] = useReducer(reducer, initialArg, init);

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

UpperCod commented 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 🤔

ofhouse commented 2 years ago

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.

UpperCod commented 2 years ago

I have generated some changes to the PR, I will wait for your Review before generating the Merge

UpperCod commented 2 years ago

Ready merged 🎉, Thanks for your PR, I will be attentive to what you need