-1

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.

2 Answers2

-1

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).

Ben
  • 2,200
  • 20
  • 30
  • So, if I do not use this header does it mean that user downloads it more than once while viewing my website? – Murad Taghiyev Jan 10 '23 at 11:37
  • @MuradTaghiyev Without these headers (and without other caching headers) the result should be cached but for some browsers it may have a very short expiry (minutes or hours) – Ben Jan 11 '23 at 14:09
-1

Yes, react stores images in cache memory. So it downloads the image only once and if you use the same image in other routes, it will not download it again. For example, you can look at the following video, the image is downloaded only once, and when the route is changed, the image is not downloaded again

Test sample