candlefinance / faster-image

Fast image loading for React Native backed by performant native libraries.
https://candle.fi/discord
MIT License
599 stars 28 forks source link

How is prefetch supposed to work? #71

Closed dlayton66 closed 8 hours ago

dlayton66 commented 2 days ago

Hi there,

I'm trying to make images on every screen in my main stack load instantly once the stack has loaded, so I'm trying to implement your prefetching in the file where my main stack navigator loads. It's a bit unclear to me how to implement this, but here's what I'm trying:

const groupImages = useSelector(getGroupImages);

useEffect(() => {
  const prefetchImages = async () => {
    await prefetch(Object.values(groupImages))
  }

  prefetchImages();
}, [groupImages])

I didn't see anything in the example about storing and referencing the prefetched images later, so I was wondering if simply referencing the same URL later automatically grabs the prefetched image. In my case, Object.values(groupImages) contains all the URLs I reference in other screens.

However, having the prefetch in or commented out doesn't seem to have any effect on behavior. In both cases, they take a second to load initially (but are instantaneous after that). Am I doing something wrong or misunderstanding how this is supposed to be implemented? Any help is much appreciated - thanks!

gtokman commented 18 hours ago

@dlayton66 the prefetching behavior of Nuke is defined here: https://kean-docs.github.io/nuke/documentation/nuke/prefetching.

Let’s say, there are 32 items on the screen (the last row is partially visible). When you open it for the first time, the prefetch API asks the app to start prefetching for indices [32-55]. As you scroll, the prefetch “window” changes. You receive cancelPrefetchingForItemsAt calls for items no longer in the prefetch window. When the user goes to another screen, you can either cancel all the prefetching tasks (but then you’ll need to figure out a way to restart them when the user comes back) or, with you can also pause them.

I think we do need to expose the cancel prefetching method to JS. Let me see if I can add that this week. Also there maybe be a bug, I'll match Nukes behavior based on their example app.