4 ms·
> It's sad that it needs to exist but that's the current state of engineering. Wait, wait. I'm trying to make friends with React for less than a month and I do
by jve 4y ago
> It's sad that it needs to exist but that's the current state of engineering.
Wait, wait. I'm trying to make friends with React for less than a month and I do appreciate this article giving me some understanding about the primitives react gives me and when to use it (Or how you called it screws/nails)
I did understand more, but I'm left with a feeling I cannot follow the "flow" of the useEffect as I couldn't understand how can items !== prevItems EVER be true?
// Better: Adjust the state while rendering
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null);
}
useState doesn't return immediatelly? Or does it cause immediate re-render? I kind of gathered from the article that all useState calls cause re-render whenever it encounters return.
- sfilipov 4y agoI am not sure I understand your confusion but here's a few pointers in no particular order: - the argument passed to useState is initial state, not "forever state". It will seed prevItems for the first render. But later when items prop changes, it's on you to detect the change to what you have as prevItems so far and call setPrevItems yourself. - items is coming as a prop from outside, prevItems is whatever you set it to last time using setPrevItems - calling a state setter (setPrevItems / setSelection etc) will always cause a rerender. That's why if you don't have the if condition you have just created an infinite loop - you are inside a render, and if you unconditionally call setX that causes another rerender later etc etc - that's why I am not a big fan of this particular "Better" example and prefer the later "Best". Avoiding calling state setter function from inside render will make your life easier.
- nightpool 4y agoWell, in the first place, this code snippet has nothing to do with useEffect, so I'm not sure why you're bringing it up. They have a separate page that they linked to that explains this pattern in more detail: https://react.dev/reference/react/useState#storing-information-from-previous-renders https://react.dev/reference/react/useState#storing-informati... But to summarize that page briefly, useState will always return the current value of the state and a function to set it. But "items" here is being used as the default value that's provided the very first time the component is rendered, when the state doesn't exist yet. In subsequent renders, the state exists, so "prevItems" will reflect the last value that was set with `setPrevItem`, not the current value of `items`
- jve 4y agoI did read the other page and google around... but you and the other comment nailed it for me, thanks.
- deleted 4y ago[deleted]