ericjam
ericjam

Reputation: 1519

What are React Native's caching behaviors for fetch

What currently are React Native's default behaviors for caching in fetch calls? The official FB guides simply say "look at Mozilla!" but we're not on a web browser. I would assume cache behavior is custom here as result of the middleware.

Let's say I do: fetch("https://exampleserver.com/myfile.json")

Knowing at least some of this would help decide whether I need to write custom caching situation with AsyncStorage like so https://gist.github.com/dslounge/18e555250a8df1f8218d702b21910eeb

Upvotes: 10

Views: 6436

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66292

React Native’s fetch API bridges to NSURLSession on iOS and okhttp3 on Android. Both of these libraries strictly follow the HTTP caching spec. The caching behavior will depend primarily on the Cache-Control and Expires headers in the HTTP response. Each of these libraries have their own configuration you can adjust, for example to control the cache size or to disable caching.

The cached files are not guaranteed to persist until they expire. The system can purge them whenever it wants.

If you make three requests really fast then you will, in general, succeed, because the caching is neither immediate nor guaranteed.

In general: set your HTTP response headers appropriately, but don’t rely on HTTP caching to behave a certain way for the proper functioning of your app. If you want a guarantee that a second request won’t actually make a network connection, you need to write that yourself.

I don’t think Expo affects this.

Upvotes: 12

Related Questions