Current section: Layout Computation 36 exercises
solution

useLayoutEffect

Loading solution

Transcript

00:00 So, you might have noticed that we're kind of cheating here a little bit. This typically happens so fast that you don't even know that it's a problem, and I had to artificially slow down rendering just so that we could observe this problem. So you notice, like, that's happening really fast. You do not see that there is a problem here.

00:18 And so this is going to be the reality for you most of the time, and this is what makes use layout effects so tricky, is you're not always sure that you need it, and you don't want to have to test every single component that's using use effect. In fact, some of them are going to be libraries, and so you don't even know that they're using use effect.

00:36 And so here's the rule about when to use use layout effect. If what you are doing in the use effect is going to impact the way that something looks in the UI, on that initial render especially, then you are going to want to use use layout effect. That's the basic rule. And so that is the case for us.

00:55 If we're doing some measurements and then we're making a state change, this is definitely going to affect the way the UI looks, and so we're going to use layout effect from importing from React, and that will make sure that this runs synchronously before, right after the

01:10 DOM has updated, but before the user gets to see what happens, so that we don't have that jumping experience. So that solves our problem, and it looks way better. If you want to be challenged, then you could figure out how to make it so that the tooltip isn't clipped off on the right side, or you can just use a library that does this for

01:30 you. But this is what the library is likely doing, using use layout effect to prevent the user from seeing the incomplete UI. There you go, that's use layout effect.