TLDR: it doesn't work. You can't ever have a React hook that exports memoized global values. EVER. This is my finding here.
I had forgotten the JavaScript essentials due to the React essentials.
useMemo() caches values and recalculates when the deps change, right? So, when I return an object from a hook like useCartItems(), all components that use the hook should be re-rendered, right?
Right???
Having the muscle memory that top-level code in a regular JavaScript file are executed only once, and that the exported values of a file are cached - I mistakenly wrote code thinking the returning values of a hook are being cached as well.
A wrong assumption.
And the result is 2 days of painful debugging.
From a JavaScript POV, I should've at least noticed the '()' at the end of useCartItems(). Meaning, the hooks (which are JavaScript function declarations) are being invoked every time.
So, the add, remove, etc operations in this returning object { list: Object[], add: Function, remove: Function, ...} are localized.
So, the const ci = useCartItems() instance for the modal and for the are never in sync. They are separate and localized, not global.
Conclusion
Rookie mistake. Should've used Zustand global stores or the Context API from the get-go - instead of taking up a challenge to explore unorthodox approaches :D

Top comments (0)