Home > other >  Does React stores and knows the images?
Does React stores and knows the images?

Time:01-10

I am a junior and this confuses me. I mean, if I use the same image more than once (on different routes) in React, does it mean that user downloads it more than once in browser?

I am just trying to learn that if using the same image will not cause more bandwidth in my website.

CodePudding user response:

Provided that you are serving the image with the correct headers, the browser should cache the image without you needing to think about it. This behaviour does not depend on the frontend framework that you're using (react, vue, angular, etc). I would read up on HTTP caching here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching

For most purposes, if you have an image that never changes, the browser will only load it once and subsequent requests for it will be served from the user's harddrive. There are a million caveats (for example if the image is requested from a different origin than it was cached from), and the image is evicted from the cache (for example because the user's harddrive was full), but the only thing you need to worry about is if your image host is sending the correct headers.

In most cases with simple images requested using the <img src="example.com/pic.jpg" /> tag, this just means making sure that either the Expires or Cache-Control: max-age headers are set and have reasonable values.

For example, sending Cache-Control: max-age=86400 would keep the file in cache for up to 1 day (86,400 seconds).

CodePudding user response:

There are a couple ways I can think of to cache the image for multiple uses on your website.

1: setting the Cache-Control header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) on the server resource will tell the browser how often it should look for updates to that resource.

2: using service workers (https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) you can choose which resources are cached and for how long from the client application.

Also note: some browsers may automatically cache image files for the current web session.

  • Related