DEV Community

Mayur Sonawane
Mayur Sonawane

Posted on

Hare-Pulling Experience: Image Downloads in React Native

Working with React Native is a lot like adopting a pet bunny. It's cute, versatile and runs on all platforms... until it doesn’t. I'm talking about the time I decided to give my app the task of downloading a mountain of images from a server. A Herculean task? Sure. But we've got our furry friend, the hare, right?

Thinking the hare would spring into action and hop through the task with a flurry of simultaneous downloads using Promise.all(), I sat back with my cup of coffee, ready to witness the spectacle.

const downloadImages = async () => {
  /* Our eager hare's concurrent downloading code */
}
Enter fullscreen mode Exit fullscreen mode

What happened instead? Our bunny had a meltdown! It could only manage to download 497 out of a whopping 1644 images, and that too while playing hide and seek with the progress report. Turns out, our bunny was more like a very confused tortoise on a sugar high.

Time for a different approach. But with Expo being the diva it can be at times, the game was on!

The Big Batch Bake-Off

Expo often gets a bad rep due to its limitations, but it shines when it comes to device capabilities. Taking inspiration from a reality cooking show, I decided to break down our download task into bite-sized portions. And thus, the batch processing code was born, taking into account the device's RAM, CPU, and OS version:

async function getBatchSize() {
  /* My version of the Great British Bake Off, but for batch sizes */
}
Enter fullscreen mode Exit fullscreen mode

Synchronizing the Tortoise... Wait, What?

As fun as watching a hyperactive tortoise would be, the reality was surprisingly effective. I created a function that methodically downloaded images one at a time. And here's the kicker – it was faster! A whopping 2.5 times faster. The tortoise was on a roll!

const handleDownload = async (imageUri, productId) => {
  /* Where the tortoise comes to the rescue */
}
Enter fullscreen mode Exit fullscreen mode

Progress Update: It's Not You, It's Me

My initial plan to report download progress based on images turned out to be as confusing as a bunny in a lettuce field. Instead, I decided to focus on the number of products processed. Clear, simple, and no more confusing the hare with complex calculations.

for (let i = 0; i < products.length; i++) {
  /* Progress reporting - tortoise style */
}
Enter fullscreen mode Exit fullscreen mode

The Moral of the Story

In the end, it was our slow and steady tortoise that came out on top, nailing all the downloads and providing accurate progress updates. The hare? Well, it's taking a much-needed nap.

So, whether you're wrangling a rabbit or managing a meltdown, remember - sometimes, taking it slow can help you win the race, even in the fast-paced world of programming!

Top comments (0)