Current section: Layout Computation 36 exercises
Problem

useLayoutEffect

Loading exercise

Transcript

00:00 We've got ourselves a little problem. We have this use effect that measures our position for our tooltip, gets the bounding client rect, so it knows whether to put the tooltip above or below the target where the tooltip should go. Then we set the tooltip height, that triggers a re-render so

00:19 that it renders in the right spot. The problem is, if we're on a lower end device or we've got a lot of complicated stuff going on on the page that's making things a little slow, this is observable while we're waiting to determine, okay, what is the position of this thing?

00:36 Yeah, that is like terrible user experience here, and the situation is like some of these need to be rendered below, and that's why we have to have this measurement. So we render above by default, but if it's too close to the top, then we'll render it below. That's what's going on.

00:54 So we need to change this to useLayoutEffect, because we need to make sure that we perform our measurements before the user has a chance to see the thing in the wrong spot. So that is your job. It's a very quick job, but hopefully you understand what's going on to actually understand why you need to do this,

01:14 and when you would use useEffect over useLayoutEffect or vice versa. So have a good time.