Tamir
Tamir

Reputation: 625

Using react hooks in conjunction with redux-saga (or any other middleware)

This question was already asked here before, however I didn't find yet any proper answer, just wonder if I missed anything or if indeed this is currently not possible.

Specifically, there are 2 main differences between hooks & redux-saga (or any other middleware):

  1. in redux-saga I can trigger code execution on action dispatch, while in hooks I can trigger code execution only on state change. These 2 are not always equivalent
  2. hooks must exist in context of component, however some "background" logic (such as initialization, location detection, etc), is not related to a specific component. In redux-saga I have the flexibility to define it in "global scope", while in hooks I must attach it to some "random" component (probably App or any other high level component).

So, is it possible to "bridge" somehow between these 2 approaches, or should I simply pick the most appropriate technique for each specific case ?

Upvotes: 2

Views: 3639

Answers (2)

Drew Reese
Drew Reese

Reputation: 202618

They are different tools to solve different problems. Hooks work internally to a functional component's state and lifecycle. Redux works internally to an entire react app's state and lifecycle. Sagas help wrangle asynchronous effects like external data fetches.

Generally speaking you want to limit the scope of variables and logic as much as possible. If a specific piece of "state" is only relevant to a single component, then keep it in component state. But if several components or the application itself needs it, then store it in app state. Same applies for asynchronous calls. If a single external call is used by only one component, keep it there, but if multiple components can make the same external async calls, then let the sagas handle them.

You are free to use as much, or as little, as is necessary of either in each component to solve your problem.

Upvotes: 3

amik
amik

Reputation: 5909

  1. In Redux-saga you can execute code only on action dispatch. Hooks are more generic, for example with the useReducer hook you can trigger code on action dispatch, with useEffect you can trigger code on mount/update/unmount etc.
  2. Redux-saga also exist in context of a component, or more precisely, whole Redux exists in a (usually top-level) store provider component and Redux-saga is only one of its middlewares. So basically if you have some global app logic and put a hook for it in your App component, it is not some random component, it is the right place to put the logic to.

I've also recently found a simple library https://www.npmjs.com/package/use-saga-reducer that introduces sagas to React's useReducer. (I'm still not sure it is a good idea - just because you can doesn't mean you should, for me hooks async functions are usually enough, but it is at least interesting)

Upvotes: 0

Related Questions