Search code examples
react-hooksredux-sagareact-statereselectuse-reducer

Can we use customHooks into redux Saga function


Following custom hooks as state selector and using that within "functional View" component. Now, I need to use that in redux Saga function. Can we use that into Saga function or I have to use some other approach instead of using custom hooks into Saga function ?

export function useSelectAllEntries()
{
return useSelector(
({allEntries=[]}) =>[...allEntries],shallowEqual
);
}

export function useSelectFilteredByMakeEntries()
{
const selectAll = useSelectAllEntries();
return selectAll.filter(...);
}

export function useSelectFilteredByCreatorEntries()
{
const selectAll = useSelectAllEntries();
return selectAll.filter(...);
}

Solution

  • Instead of defining these as custom hooks, define them as selectors instead. Redux selectors may be freely shared between multiple different use-cases.

    export const allEntriesSelector = ({ allEntries = [] }) => allEntries;
    
    export const allEntriesFilteredByMakeEntriesSelector = state =>
      allEntriesSelector(state).filter(...);
    
    export const allEntriesFilteredByCreatorEntriesSelector = state =>
      allEntriesSelector(state).filter(...);
    

    Then, when you want to use them in a function component, just call useSelector:

    function MyComponent() {
      const entries = useSelector(allEntriesSelector);
      const filteredByMake = useSelector(allEntriesFilteredByMakeEntriesSelector);
      const filteredByCreator = useSelector(allEntriesFilteredByCreatorEntriesSelector);
    
      return (...);
    }
    

    and when you want to use them within a saga:

    import { select } from 'redux-saga/effects';
    
    function* mySaga() {
      const entries = yield select(allEntriesSelector);
      const filteredByMake = yield select(allEntriesFilteredByMakeEntriesSelector);
      const filteredByCreator = yield select(allEntriesFilteredByCreatorEntriesSelector);
    }