Introducing useDispatch and useSelect

Coming soon via the pending Gutenberg 5.9 plugin release (and the subsequent @wordpress/data package release) are two new apis to use in implementations interacting with the wp.data api. useSelect and useDispatch are custom React hooks that enable a more declarative interface to registered stores in the registry. In this post I’m going to try to give some highlights of these new apis.

What happens to withSelect and withDispatch?

The short answer is, “nothing”! withSelect and withDispatch are still usable and are not being deprecated. In fact, under the hood they have both been refactored to use hooks also.

There’s no pressing need to retire these interfaces so you can reliably keep on using them!

Why?

React hooks are becoming an important api in the react ecosystem and this article written by Dan Abramov is a good introduction to them including some of the rationale for why the api was created. For the use case in Gutenberg, the same reasons for hooks in general contribute to why they are being implemented here. Namely:

It’s hard to reuse stateful logic between components

As higher order components, withSelect and withDispatch do a great job at enhancing components to connect with the wp.data registry. However, they contribute to the “wrapper hell” commonly experienced in large react apps where stateful logic is shared between components.

Hooks provide a better primitive for interacting with stateful logic and useSelect and useDispatch in turn provide declarative interfaces for interacting with the store state without changing component hierarchy.

Complex components become hard to understand

While much of the complexity of interacting with store state is reduced in the usage of withSelect and withDispatch. The new hooks take this a few steps further:

  • The api is simplified.
  • The declarative behaviour is more straightforward to follow in the context of their implementation. Instead of having multiple withSelect or withDispatch calls, you can now embed useDispatch and useSelect within the components using them (or, preferably, create a custom hook implementing the multiple useSelect and useDispatch hooks and exposing only the props needed by the component).

Classes confuse both people and machines

While this applies more to hook usage in general, it does allow for not worrying as much about lifecycle methods and for implementing directly in functional components. Note, withSelect and withDispatch could also wrap functional components, but the exposure of hooks allows for integrating with the usage of other React hooks.

How?

There will be documentation updated in @wordpress/data docs eventually, but for now, you can see the api and examples directly in the repository.

I’ve also written an overview/introduction to the hooks that gives some insight into usage.

#wordpress-data, #gutenberg, #javascript, #usedispatch, #useselect