Some computations inevitably take longer than this. When they do, React Native gives you a couple of options:
- Port the operation to native code and run it in the background.
- Use the
InteractionManagerto run it after animations.
'next-frame' is designed to be a third option. It allows you to break up an expensive computation into smaller parts and run just part of it on each repaint. This maintains the responsiveness of your UI while the computation is still ongoing.
This quick start assumes that you're already familiar with the
await keywords, which you can read up on here. Async and await are enabled by default in current versions of React Native, so this pattern works in RN out of the box.
For the previous example, let's assume that we get several hundred recordings back from the server as an array, and each one takes about 1/100th of a second to process. Normally processing all of them would take several seconds, and would cause unacceptable lag. However, using
await nextFrame() we break up our computation and have much better perceived responsiveness.
In the common case (like the one in the example above) that you just want to iterate over a collection and process one element per frame, we've included a convenience function
mapInFrames that does exactly that. Here's the same example, rewritten with
;let response = await ;let recordingsJSON = await response;await ;
Easy, and not imperative at all. 😃
Under the hood
This library was developed with React Native in mind and has only been tested there. However, it should work fine in the browser as well.