by matsemann · 1y ago · 0 comments
A second but unrelated grief with hooks is when you get async updates happening in between renderers where you want to update some state and then do some logic. Let's say I'm waiting for 2 requests to finish. They both should update a value in my state. However, to not lose an update if both happens at the same time, I need to do the setState with a callback to see the latest value. But then, what if I want to trigger something when that new calculated state value is z? I can't do that imperatively inside the callback, and outside it I can't see the new value and don't know that I now should do something additional. I have to do it in a useEffect, but that decouples it too much, the logic belongs where I want to put it, in my state hook. Not in some useeffect wherever. The other option is to misuse refs to also maintain a current state there in addition to the useState. So always use the ref, but set the state in the end to trigger a re render.
Hooks are so unelegant for real problems. I hate how they force your hand to write spaghetti.
Components seem extremely similar to classic OO, why can't I use the same syntax.
If y never changes it should be declared as a const function outside of the context of the component, then it can be safely included in the dependency array without triggering unnecessary rerenders.
If y does change, you've just created a bug where your component will keep using an old version of y.
React is a closed ecosystem. Anything that enters either do through the root component or through hooks (in the functional version). If both x and y enters the ecosystem, they must adapt to the rules, meaning you write what happens when they change. Because the only reason for them to enter is that they are not constant outside React's world (which is the ultimate truth). If they are constant, then just use the reference directly.
Arugably this isn't a misuse, but just accepting that Reacts state management isn't powerful enough for what you need. Something akin to useRef + useSyncExternalStore is often what developers want.
For example, there's no guarantee that your useEffect will be invoked with the intermediate state you wanted to observe.