Hacker News new | ask | show | jobs
by hombre_fatal 562 days ago
How do you write a singleton service that can feed state back into the component that calls it when that state changes?

For example, `api.fetchInfo()` would want to feed Loading | Success(T) | Error(E) back into the React component call-site when they change.

EventEmitters come to mind but aren't without their own issues like subscription leaks. And you have to track component arguments in order to know when to call the service again when they change which is a classic source of complexity.

Hooks provide a solution for this since they themselves are just nested React lifecycle constructs (like useState + useEffect).

1 comments

In class components you just could await the result and perform a set state, and that would be it. Easy as pie. But now in function components when everything is called all the time without your control you have to use escape hatches like use effect just to work around react.
Hooks let you wrap all sorts of logic (and other hooks) and return values that rerender the callsite component when changed. Just keep adding on to my hook example and you get more and more code that you need to repeat in every class component that uses it.

Of course, the class component solution to this was to use an HOC, but that had its own issues like complex data flow and wrapper hell.

Hooks solve problems of composition without Yet Another Wrapper and they give clearer data flow, better ref forwarding, etc.

It's easy to see complicated useEffect spam and blame hooks but frankly that wasn't any better when it was happening at different layers of HOCs.

You can just use a service instead, expose public methods and hide private while keep expending and refactoring the internal logic. The same way it’s been done for decades. The only problem is the one that react created for itself in function components which is when to refresh the render from the state.