I spoke in a previous article about useLayoutEffect hook, & where it should be used (changing something after doing some DOM measurements). & because these cases are not very common (<5%), some people asked for a real-world example to fully grasp it.
And very luckily, I encountered such a case this week! So I decided to share it with you guys & hopefully you'll get a better understanding of the hook.
I was working on the "products" page of the makers.bolt.fun platform, and in this page, we have several rows of apps for each category. Each row is actually a carousel of cards. And the carousel requires passing the number of items to be showed at once as a prop. However, what we needed wasn't a fixed number of items, but a fixed width for each card (296px) and some spacing between them. And it's easy to calculate this dynamic number of items, we just get the width of the carousel container, then we divide it by the width we want for each card (296) + gutters.
And I went to do just that. 1- I created a ref for the carousel container 2- Put this ref on the element. 3- Inside useEffect, did the calculation to get the number of items needed. 4- And then pass it to the carousel.
. . While this did work, but there was a problem which you might have guessed it by now. The first time the component is painted, the ref isn't assigned & useEffect isn't called yet, so the number of items isn't calculated (0), which resulted in the carousel appearing empty for a short moment (see the first image below).
So what we needed was to do this calculation after the ref is assigned, but before the component is painted to the screen, and where could we do that??
Yup, you guessed it. Just use useLayoutEffect instead of useEffect. And the problem is solved!!
I hope things are now very clear for everyone. & if you still have any questions, feel free to drop them below.
That's it folks. Leave a like if you found this useful 👍.
And have a nice day 👋.
About Me
I'm a freelance web developer who specializes in frontend.
I have a special love for React. And my personal goal is: Building things that are Awesome! ✨
If you are someone who is building a project where high quality is a MUST, then Let's Chat! I'll be glad to help you with it.