Current section: Dynamic Promises 29 exercises
Problem

useTransition

Loading exercise

Transcript

00:00 One thing that you'll notice as we navigate between these different ships is that we go to our loading state, and that's kind of annoying. Of course, once it's cached, then it's going to be instant, and that's awesome. But it is kind of annoying to have to go to that loading state, especially if the request is really fast or whatever.

00:17 And so it would be nice if we could just leave the old stuff up for a second while we're waiting for the new stuff, but still give the user some sort of feedback that like, yes, I know you're trying to get to the interceptor, just give me a second while I do that. But not just such a huge jarring thing like, whoa, interceptor!

00:34 Like, oh no, I want to have it be a much more smooth transition to the next thing. And that is what transitions are all about. We want to transition to the next thing. So useTransition is a hook that comes from React. We get a tuple, this isPending, and startTransition.

00:52 And so anytime you have a state update that's going to trigger a suspense boundary, like in our case, changing the ship name is going to trigger a suspense boundary. So you wrap that in a startTransition like this, and then any suspending thing that happens

01:09 in the process of changing that UI, React will actually hang on to the old UI while the new UI is being generated in the background. And it will also give you an isPending so that all of the previous state and everything will still be there. Even the resolved promises and everything, that will still be available to you.

01:30 But you also get this isPending so you can display some sort of loading state of some kind. In our case, our designer said, hey, just give this an opacity of 0.6. And that will be enough indication to the user. You probably have a better designer than I do, which is myself.

01:47 But yeah, so that is what we're going to be doing in this exercise step, is adding a transition so that we get a better user experience.