Reputation: 11
Using image component to display image from an external server in react native. but image is not updated if we change image in server with same URI. if we use query string to URI it reloads the updated image. Following code works
<Image
style={styles.logo}
source={{ uri: this.state.photoURL + '?' + new Date() }}
/>
Does the above code cache image for every re-render and eats memory? React image component does default caching and how caching works in image component? Best way to handle image in react native considering caching and updated image in the server.
Upvotes: 1
Views: 2325
Reputation: 2473
Yes, the above example will cache a new image on each re-render of the component. It doesn't eat memory, it eats the storage on your phone.
You can read more about caching of the RN Image
component here (cache is also supported only for iOS currently): https://facebook.github.io/react-native/docs/images#cache-control-ios-only
If you want to have a proper image cache solution for Android, you'll need to use a third-party package or write your own solution.
The way you usually want to manage cache control is with timestamps, just as you did. However, you would not use Date()
to dynamically generate the timestamp and force the app to look for a new image.
I am assuming you get the image url from some API. Include the timestamp of when the image has been updated the last time into the response, so this.state.photoURL
already has ?${lastUpdatedTimestamp}
attached by itself.
Or alternatively let the API return a photo object instead of a photo url, like this:
{
...
photo: {
url: "https://someserver.com/some/image.png",
updatedAt: "1569110591504"
}
}
And then you can do
<Image source={{ uri: `${requestData.photo.url}?${requestData.photo.updatedAt}` }} />
Upvotes: 2