@@ -21,6 +21,32 @@ type Result =
2121 error : Error ;
2222 } ;
2323
24+ const isSameSource = ( a : AsyncImageSource , b : AsyncImageSource ) => {
25+ if ( ! b ) return false ;
26+
27+ if ( isHybridObject ( a ) && isHybridObject ( b ) ) {
28+ return a . equals ( b ) ;
29+ }
30+
31+ return JSON . stringify ( a ) === JSON . stringify ( b ) ;
32+ } ;
33+
34+ const shouldClearState = ( source : AsyncImageSource , result : Result ) => {
35+ const { image, error } = result ;
36+
37+ // If there was an error, we need to clear the state
38+ if ( error ) return true ;
39+
40+ // If there is an image, we check if the source has changed
41+ // if not, we don't need to clear the state
42+ if ( image && "__source" in image && image . __source ) {
43+ // @ts -expect-error - We save the source on the JS side so we can diff it
44+ return ! isSameSource ( source , image . __source ) ;
45+ }
46+
47+ return false ;
48+ } ;
49+
2450/**
2551 * A hook to asynchronously load an image from the
2652 * given {@linkcode AsyncImageSource} into memory.
@@ -37,8 +63,7 @@ export function useImage(source: AsyncImageSource): Result {
3763
3864 // biome-ignore lint: The dependencies array is a bit hacky.
3965 useEffect ( ( ) => {
40- // clear state each time we will load a new image
41- if ( image . image || image . error ) {
66+ if ( shouldClearState ( source , image ) ) {
4267 setImage ( { image : undefined , error : undefined } ) ;
4368 }
4469
0 commit comments