'REACT - Accessing state with in useEffect callback

I've made an example of my question. I'm building a simple component that should manage the size of its children, but before any manipulation, needs to know the children's initial size.

So every child reports its own size on useEffect to the parent component, and parent component must keep the widths of all children, but only keeps the last one.

https://stackblitz.com/edit/react-ts-fdqv7x?file=index.tsx

the question is Why the value of widths is empty on line no: 26?



Solution 1:[1]

When you're calling setWidths you want to pass a callback that gets the latest state value, like this:

setWidths((w) => ({ ...w, [index]: width }));

Demo: https://stackblitz.com/edit/react-ts-kzgjfv?file=index.tsx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 coglialoro