๐Ÿ–ผ๏ธ Prefetching Images in React Native

February 20, 2018

It’s a common scenario to display images that are hosted on a remote server. There’s great built-in support for this with React Native. However, if you start loading the image at the instant you need to display it to the user, you may end up displaying some loading progress or perhaps the user won’t even stick around long enough to see the image.

While working on an optimisation task, I came across some interesting methods for accessing the native image cache. It’s worth noting that the documentation for these methods is quite limited with the current version of React Native at the time of writing (0.53) - so your mileage may vary!

If your application is architected in such a way that you can anticipate scenarios where remote image resources need to be displayed to the user you can pre-emptively begin to load these into the image cache. Hopefully, by the time the user visits the screen containing the image, the image will have already been primed into the cache.

This is actually really easy to achieve with a single line of code:

import {Image} from 'react-native'

...

Image.prefetch(REMOTE_IMAGE_URL)

Of course, if the images that you’re trying to display are so big that you need to prefetch them well in advance of being displayed, you might want to consider optimising the compression of them or even bundling them into your app’s binary before considering this prefetch technique ๐Ÿ˜„.

comments powered by Disqus