
Lesson Description
The "useSyncExternalStore Hook Exercise" Lesson is part of the full, State Management at Scale in React & Next.js course featured in this preview video. Here's what you'd learn in this lesson:
David instructs students to refactor code for an exercise by replacing useEffect and useState with useSyncExternalStore to sync flight information. Using subscribe and getSnapshot makes the code cleaner while preserving update functionality.
Transcript from the "useSyncExternalStore Hook Exercise" Lesson
[00:00:00]
>> David Khourshid: Okay, so in this exercise, we are syncing with an external store, and this external store is responsible for showing us a bunch of flight information. And it updates every second or so. You could see that some of the statuses are changing, some of the gates are changing.
[00:00:20]
This is a very chaotic airport that we're modeling over here. And what's happening is we're subscribing to this store to get these flight updates. The way that we're doing that is we're using useEffect to subscribe to this flight store, and we're setting the flights and putting them in use date and then we're returning the flights.
[00:00:43]
So just to get used to USYNC external store, I want you to take a couple of minutes and refactor this so that instead of UseState and UseEffect, we use the USYNC external store hook. All right, so let's refactor this. We're going to use SYNC external store. And again, it's going to take three arguments.
[00:01:10]
The first one is a way to subscribe to the flight store. And so we could just pass subscribe here because looking at the implementation, we already have like this way of subscribing and unsubscribing. So whenever we get new data, it's going to basically add the callback to the listeners and then call those listeners.
[00:01:33]
So we get those flights and we also have a way of getting the snapshot. So flightStore.getSnapshot. And since the snapshot is going to be the the same whether it's the client or server, we could also safely pass in this snapshot for here as well. And typically when you're using this with external systems and not browser APIs, you'll realize that the client and the server snapshot are going to be the same.
[00:02:02]
So the return value of here is what we're subscribing to. So we could say const flights equals USYNC external store with all of that data, and we're going to see that the end result is pretty much exactly the same. So we're still subscribing, but we have a much more concise way of doing that.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops