Current section: Responsive 29 exercises
solution

useDeferredValue

Loading solution

Transcript

00:00 Here is our ship search component, and we've got our useTransition, that's our transition pending, and we've got spinDelay and all of that stuff. This is all great, except that we are transitioning our onChange, and the value that shows up here comes from this thing that's happening in the transition.

00:18 That is not going to work. We're going to remove the useTransition, and call useDeferredValue instead. UseDeferredValue with the search, and that's going to get us our deferred search value. This is going to allow React to branch and render our component in two instances,

00:38 and our isPending now comes from whether isPending. Oh, come on. Well, okay, I guess we can just put it right in there. That's what the AI wants us to do. Okay, AI, I'll listen to you. We have our deferred search, so if this is the render where they're different, then we'll be pending,

00:57 and if this is the render where they're the same, when deferred has caught up to the search, then we're no longer pending. We're going to use the deferred search as our mechanism for the search results. This is the thing that we want to have.

01:14 Here we go. That's what we want to have for the pending state. We're going to provide the previous value or the value that's falling behind so that we can still show the old UI in the search results. Then React will also have a version of deferred search,

01:34 which is equal to the latest version of deferred search. We'll pass the latest version to search results. In that case, that will suspend. React will be like, okay, cool. I'll show the UI that has the old version of deferred search until the new version of deferred search is ready to render. It's no longer suspending.

01:53 The other thing we'll need to do is remove that start transition and that will get us in a good state here. Now, we'll pull up our DevTools, we'll set it to fast 3G, and I'm going to search for the medical ship. There it is. Sweet. We can get a very responsive UI and still

02:10 get our pending UI all in place the way that we want it to be. This is because React is able to just say, okay, let's render it with them being the same. Let's also render it with the deferred being the previous value, so it's a step back from the current latest value.

02:29 That way, we can render what we used to render, what was working before, and we'll try to render the new thing. If that suspends, we'll just wait for that. We'll keep this old thing around. Then once that thing is done, then we can bring them both together. That allows us to have our search up-to-date constantly

02:46 and our deferred search be used for rendering our search results. That way, our UI can be totally responsive, but we still can manage the suspending for our search results.