We're doing that by putting isOpen in a dependency, which is going to trigger the Use Effect. You can see here, we're clicking, state's changing, then we have an effect. Lots of indirection. So, instead, get rid of the Use Effect, put it directly in the event handler, and now it becomes much more straightforward and easier to understand. So, now instead, we are just calculating the next state, because we know the next state of that is open, and depending on that state, directly call onOpen and onClose. And then you could even put it inside of a hook.
So, all right. You don't need Use Effect for subscribing to external stores. This one is a really interesting one, because it sort of goes counter to what I was just talking about. It's like Use Effect is really good for subscriptions, right? Well, over here I'm subscribing to a store API, and all I'm doing is getting some specific value, like whether I'm connected or not to the store API, and then I have an unsubscribe here. So, we're still a little bit of an indirection here because we are setting a local state variable. Guess what? You could actually get rid of this and use the useSyncExternalStore hook, which has three parts. A subscribe part, where you tell it, here's how to subscribe, here's a function you need to call to subscribe, the getSnapshot part, which is, this is the value that I want to get, and here's how to read it from that store, and a server snapshot where it's just good for SSR. So, you put all those three things together, it's going to automatically subscribe and get you the value you need, no use date, no use effect. It's a really brilliant hook. So, I do recommend that you at least try it out. They say it's only for library authors, but they also said, like, do not use, or you will be fired, it's only for React maintainers, but we're seeing libraries use it for whatever reason, like Preact Signal and stuff like that. So, go ahead and use it. Not that one. But use sync external store.
All right. This one is a big one. You don't need use effect for fetching data. Like we talked about in the beginning, that was one of the big reasons that we used use effect. So, instead of all of this that we were doing before, just use the framework. Whatever you're using, you're likely using a framework. Remix has a really nice loader over here. get server side props. This is going to be available to you directly in the component. And then there's a library that hopefully most of you are using for fetching data, which is React query.
Comments