I have a react app where I am using 'react-image-pan-zoom-rotate' for showing images.
https://github.com/mgorabbani/react-image-pan-zoom-rotate
I basically have a url of external service that provides the image which I am passing to both of the below libraries to render the image.
Recently I have started facing a issue(only in Chrome) where if the cache is disabled, then whenever i click on the image in browser or use any controls provided by this component it rerenders it which results in another call to the external image server. And this happens whenever i click/interact with the image or the view generated by the above react library.
Now I have started using https://github.com/theanam/react-awesome-lightbox/blob/master/src/index.js and it does not have any such issues with cache disabled.
Any idea why this could be happening ?
I can reproduce the behavior you describe: https://codesandbox.io/s/n1rv671pkj disabling cache does cause the image to re-downloaded every time.
This is due to their implementation (that can be seen here https://github.com/mgorabbani/react-image-pan-zoom-rotate/blob/master/src/PanViewer.tsx) where they set key={dx}
<StyledReactPanZoom
zoom={zoom}
pandx={dx}
pandy={dy}
onPan={onPan}
rotation={rotation}
key={dx}
>
<img
style={{
transform: `rotate(${rotation * 90}deg)`,
}}
src={image}
alt={alt}
ref={ref}
/>
</StyledReactPanZoom>
This tells react to instantiate a new component every time the image's x coordinate changes and without cache that means re-downloading the image (try moving only vertically and you'll see no reload). To understand why the key prop causes a new instance see the react docs and this answer on Understanding unique keys for array children in React.js
Here's a gist of the explanation from the answer linked above:
React uses the key prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique,
...
It is also important that these keys remain static throughout all re-renders in order to maintain best performance.
I created a sandbox where I only removed that line and it effectively stops reloading the image.
https://codesandbox.io/s/react-image-pan-zoom-rotate-forked-tn787?file=/src/index.tsx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With