facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
228.69k stars 46.81k forks source link

[Feature Request] useDispatcher hook #16294

Closed redneckz closed 5 years ago

redneckz commented 5 years ago

useReducer can be used for local state management. And dispatch produced by useReducer can be used locally or inside underlying components.

But sometimes it would be nice to "connect" arbitrary components in tree. Some kind of global event/action bus but without global state.

As a result, I propose the useDispatcher hook in addition to useReducer: https://codesandbox.io/embed/react-hooks-usedispatcher-gw6u9

It something like pattern-based discovery in microservices. Upsream and downstream remain loosely coupled.

gaearon commented 5 years ago

The canonical way to do this is to use Context instead. https://kentcdodds.com/blog/how-to-use-react-context-effectively

redneckz commented 5 years ago

The canonical way to do this is to use Context instead. https://kentcdodds.com/blog/how-to-use-react-context-effectively

Thank you for your answer. In most cases context is really good solution. But such solution comes with upstream connected to downstream component through some container on top of components tree. That's why, "lifting state up" pattern is based on components hierarchy abstraction. In useDispatcher example I just want to address a few cases there it is better to connect components directly without some kind of container on top of them (and leaving the state local). The redux is about global state and global events bus. useDispatcher is about global events bus only. It can be organized to support different redux middlewares to connect generic logic (or aspects, like logging, offline mode support, ant etc) to containers.

gaearon commented 5 years ago

We generally try to avoid adding things to React that are easy enough in userland unless we have a strong reason to encourage a particular way of doing something. In this case it seems like it’s neither. I see why you might want this but IMO this works better as a Custom Hook rather than a core API.

redneckz commented 5 years ago

I've created micro library) https://github.com/redneckz/react-dispatcher