Skip to main content
šŸž
Dev Corner
Using WebP in React

Using WebP in React

Fewer bytes to download for the user equals better pagespeed index, better conversion rate, and in general better user experience. It is also an important factor in ecommerce SEO.

The most well-known tricks to server fewer bytes to download are:

  • Optimize the quality of the images
  • Use JPG where possible
  • Use srcset to serve different sized images for the different devices

Today though, there is another way to reduce the size of the images, the relatively new image format WebP. It supports both lossless and lossy and can be used both for images with and without transparency.

WebP Size Benefits

According to Googleā€™s own studies, using WebP will save an average of 30% of the png image size, compared to what normally is served on the web. For jpg the savings are also so good that you should favor WebP over jpg. Despite being smaller in size, it is able to retain the image quality so that you get the best of both worlds: smaller image and good quality.

This is something that we all get on board with!

Use Webp in React

The browser support for WebP is not 100% yet, at the time of writing this blog post it is at 80%. Not too shabby, but we still need to provide a decent fallback for browsers that donā€™t support it yet.

The easiest way to do this is to utilize the HTML picture element and provide two different sources, one with webp and one with the fallback. Like so:

<picture>
 Ā <source srcSet=ā€img.webpā€ type="image/webp" />
 Ā <source srcSet=ā€img.jpgā€ type="image/jpeg" />
 Ā <img src=ā€img.jpgā€ alt="Alt text" />
</picture>

Our friends at Snowball created a nice pen on Codepen for us, demonstrating how this plays out in React. The source that the browser decides to load is displayed beneath the image.

Hereā€™s is how it looks in the latest Safari.

And hereā€™s is how it looks in Chrome

Great! The browser determines which image to use, and Chrome is wise enough to choose webp. Safari has no support for WebP yet, so their users are getting the fallback jpg version instead.

Conclusion

WebP and AVIF are new formats that are taking over the web. In the above example, the WebP image is half the size of the jpg version, a super performance improvement by just using a different image format.

With Crystallize you already have this out-of-the-box. We are generating both WebP and original file format for every image you upload, ready distributed on a CDN. Best of all thatā€™s not the only benefit you get with Crystallize.

Wanna know what else we offer as an out-of-the-box feature that helps you streamline your workflow? Schedule a personalized 1-on-1 demo and let us walk you through Crystallize.