But now is a good time to mention, actually, I'm going to be sharing a slide at the end with a link to all of this code. So if you are curious, if you want to see exactly how this works, you will be able to do that.
Finally, we get that rotation value, and we apply it as a CSS transform, setting an inline style, essentially. So what do we think about this? Like, does this work? Well, it works as a prototype. It works as an MVP. But there's often, like, quite a lot of distance between, like, it works on my machine in localhost and it's production ready.
For one thing, all of this code runs a lot, like dozens and dozens of times a second. And the problem with that is that getting a client req, getting a bounding box, is kind of slow. We think about it, right? This box doesn't really change as the user moves their mouse. Certainly, it does. Actually, it changes very slightly because of the rotation. But the center doesn't change. And so, like, if we want this to be performant, do we really have to be recalculating that box dozens and dozens of times a second?
So what I'm going to do is I'm going to grab these two lines and I'm going to move them up above the event handler, so now it only does this work when I move the mouse. But this doesn't really work super well either. For example, we do need to recalculate the bounding box when the user scrolls because right now, when the user's at the top of the page, this is the distance, but as they scroll, that distance changes. So, and you see what I'm saying, right? There's this journey between the working prototype and the production-ready version.
In addition to everything I already had, I also have to add event listeners to the scroll event, I'm also using resize observer. This will tell me not only… Actually, I don't think it does tell you if the window resizes. It tells you if the element resizes or if one of its ancestors has a change in CSS that causes it to resize. So, this is better, but there's still a bunch of stuff missing. For one thing, I should be cleaning up these event listeners, right? It's one thing to start that work, we also want to stop it. Like if the user navigates away from this page, we shouldn't still be tracking the mouse position. And maybe we want to debounce this so we're not calculating it on every scroll event, because that too fires really, really rapidly.
So, let's talk about how React can solve some of these problems. And we have it now running in React. Because this is a React conference, I'm going to assume that you're all somewhat familiar with the fundamentals of React. Even if you're not, I think this will make sense. We're going to keep things pretty high level. So, like, right away, we see something kind of cool. Const mouse position is equal to useMousePosition.
Comments