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?
CodePudding user response:
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