A button loads a list of items from an API and displays them alongside a count summary. Both the list and the summary should update together after loading completes.
Click Load - three items appear in the list but the summary reads "Loaded 0 items" instead of "Loaded 3 items". The count never corrects itself on any subsequent render.
setItems and items are not the same thing - one is a command you sent, the other is a snapshot from the past.
setItems and items are not the same thing - one is a command you sent, the other is a snapshot from the past.
Why this fixes it
setSummary reads items.length - but items is the state snapshot captured when handleLoad first ran. Calling setItems(data) does not update items in place; it schedules a new value for the next render. Execution continues in the same snapshot, where items is still an empty array, so items.length is permanently 0 inside that call. Replacing it with data.length reads the local variable that already holds the fetched result - it is correct immediately, with no dependency on when React decides to commit the state update.