Optimizing use() hook in React for stable Promise reuse

Yesterday I posted about the use() hook in React and showed an example of fetching data directly inside it. Someone pointed out in the comments that this approach could create a new Promise on every render. And they were right. The use() hook expects the same Promise between renders. If a new Promise is created every time the component renders, React can keep suspending the component again and again. In practice, the request should usually be cached, so the same Promise is reused between renders. React even provides a cache() helper that can wrap async functions and return a stable Promise. This pattern is especially common in server environments or frameworks that handle request caching automatically. The key idea is that use() works best when the Promise it receives is stable across renders. #React #Javascript #WebDevelopment #Frontend #SoftwareEngineering

  • graphical user interface, text

Thanks to Rômulo Santos for pointing this out in the comments of yesterday’s post. Here’s a small example of how this works with cached requests

I think cache is not required to make it stable, you just have to make sure to return same promise, so you can use singleton pattern or just call the function that returns the promise and save it in a variable and use it where it’s required

Nice, does it work e.g. with react-query where I want to refresh user record every five minutes?

Like
Reply

I think useMemo achieves the same

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories