React blunders: close over objects

To recap the last post - one issue this combination of components faces is that the asynchronous upload method closed over functions which in turn closed over state that gets stale over time.

One of the two issues we can resolve with the useState overload that provides us with the current state:

This fixes the onItemCompleted callback. But what about onAllCompleted ?

To show you one more tool from our arsenal of circumventing staleness in function components, let’s make sure that the Uploader always sees the latest version of the onAllCompleted callback:

On every render of Uploader, we’ll write the passed in props into a ref:

And from now on we access the props through the ref:

Now the uploadAsync function has access to the last set of functions that were passed in during the last render. Once onAllCompleted is called, it is the one that sees the latest version of the items state from App.

I hope you’ll enjoy this little ref hack and you might find it useful here & there.