33

My folder structure:

|--App
  |--Components
    |--PageA.js
    |--PageB.js
    |--PageC.js
  |--common-effects
    |--useFetching.js

I am refactoring my code to fetch data from API, using react hooks. I want to dispatch an action from useEffect in useFetching.js that is intercepted by saga middleware. The action should be dispatched only when the components(PageA, PageB, PageC) mount.

I am using redux, react-redux and redux-saga.

PageA.js:

function(props) {
  useFetching(actionParams)
  //....//
}

Similar code for PageB and PageC components.

I have abstracted the reusable code to fetch data in useFetching Custom hook.

useFetching.js

const useFetching = actionArgs => {
  useEffect( () => {
    store.dispatch(action(actionArgs)); // does not work
  })
}

I don't know how to access redux dispatch in useFetching. I tried it with useReducer effect, but the sagas missed the action.

HarshvardhanSharma
  • 754
  • 2
  • 14
  • 28

5 Answers5

46

Version using react-redux hooks:

You can even cut out the connect function completely by using useDispatch from react-redux:

export default function MyComponent() {
  useFetching(fetchSomething);

  return <div>Doing some fetching!</div>
}

with your custom hook

import { useDispatch } from 'react-redux';

const useFetching = (someFetchActionCreator) => {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(someFetchActionCreator());
  }, [])
}

Edit: removed dispatch from custom hook as suggested by @yonga-springfield

Note: React guarantees that dispatch function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

Alex Hans
  • 538
  • 1
  • 4
  • 9
  • 31
    Should `dispatch` be included in the dependency array for useEffect? – pianoman102 Sep 28 '19 at 22:08
  • 14
    I'm getting an error when puting dispatch in the useEffect: ```React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps``` – imcc Jan 13 '20 at 06:38
  • 1
    @pianoman102 techincaly, yes you should. Even though the note there mentions it's identity is stable and won't change; that doesn't mean yo ushoudl omit it and the lint rule if using CRA will continue to throw. More context is described here: https://github.com/facebook/create-react-app/issues/6880#issuecomment-486640921 – Petrogad Jan 22 '20 at 19:21
  • 1
    "React guarantees that dispatch function identity is stable" source? I could not find this anywhere. – Pedro A Jun 29 '20 at 16:50
  • @PedroA https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies – Martin. Jul 19 '20 at 18:25
  • 3
    @Martin. Thanks, but what I see there is that `dispatch` **from `useReducer`** is stable, but what about `dispatch` from `useDispatch` from `react-redux`? – Pedro A Jul 19 '20 at 19:03
  • [https://stackoverflow.com/questions/56795607/what-are-the-cases-where-redux-dispatch-could-change](https://stackoverflow.com/questions/56795607/what-are-the-cases-where-redux-dispatch-could-change) – madwyatt Aug 05 '20 at 04:39
16

You would need to pass either bound action creators or a reference to dispatch to your hook. These would come from a connected component, same as you would normally use React-Redux:

function MyComponent(props) {
    useFetching(props.fetchSomething);

    return <div>Doing some fetching!</div>
}

const mapDispatch = {
    fetchSomething
};

export default connect(null, mapDispatch)(MyComponent);

The hook should then call the bound action creator in the effect, which will dispatch the action accordingly.

Also, note that your current hook will re-run the effect every time the component is re-rendered, rather than just the first time. You'd need to modify the hook like this:

const useFetching = someFetchActionCreator => {
  useEffect( () => {
    someFetchActionCreator();
  }, [])
}
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • All my components use a single action `export const fetchData = payload => ({ type: 'FETCH_DATA' })`. `sagas` will then store the value in appropriate reducer of the page by dispatching the corresponding action. According to your solution, I would have to pass reference to dispatch from each component. – HarshvardhanSharma Feb 28 '19 at 16:58
  • Any action that you want to dispatch, like the `fetchData` function you just wrote in that comment. – markerikson Feb 28 '19 at 17:12
  • I changed my code accordingly, but still *saga* `yield take('FETCH_DATA');` is not able to intercept this action – HarshvardhanSharma Feb 28 '19 at 17:21
  • 1
    I made some tweaks, it works. Thanks a ton! But I still feel that passing reference to dispatch from every component to custom hook is a bit repeating than what I could in an HOC. – HarshvardhanSharma Feb 28 '19 at 17:39
  • 2
    consider that i don't want connecting action creator to my component specially for my hook. any ideas? – Arkadiy Afonin Apr 03 '19 at 12:57
10

This is just to bring some optimization to @Alex Hans' answer.

As per the documentation here. A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.

With this in mind, we need not send a reference to the dispatch function to the useFetching hook as a parameter but rather, simply not send it and rather simply use it from within the useFetching hook with the appropriate imports.

Here's an excerpt of what I mean.

import { useDispatch } from 'react-redux';

const useFetching = (someFetchActionCreator) => {
    const dispatch = useDispatch()

    useEffect(() => {
        dispatch(someFetchActionCreator());
    }, [])
}

I can't ascertain this example will fit without errors in your codebase in your case but just trying to explain the idea/concept behind this post.

Hope this helps any future comer.

Aniruddha Shevle
  • 4,602
  • 4
  • 22
  • 36
8

Alex Hans right decision with dispatch, but to eliminate request loops to api you can specify the dependence on dispatch ( I used Redux Toolkit )

  import React, { useEffect } from 'react'
  import { useDispatch } from 'react-redux'
  import axios from 'axios'
  import { getItemsStart, getItemsSuccess, getItemsFailure } from '../features/itemsSlice'

  const fetchItems = () => async dispatch => {
    try {
      dispatch(getItemsStart());
      const { data } = await axios.get('url/api')
      dispatch(getItemsSuccess(data))
    } catch (error) {
      dispatch(getItemsFailure(error))
    }
  }

  const PageA = () => {
    const dispatch = useDispatch()
    const { items } = useSelector(state => state.dataSlice)
   
    useEffect(() => {
       dispatch(fetchItems())
    }, [dispatch])

    return (
      <ul>
         {items.map(item => <li>{item.name}</li>}
      </ul> 
    )
  }
  
  export default PageA

it is important to passed dependency parameter of dispatch in the useEffect(() => {...}, [dispatch])

FreeClimb
  • 696
  • 8
  • 13
1
useEffect(() => {
   fetchData();
 }, []);

 async function fetchData() {
   try {
     await Auth.currentSession();
     userHasAuthenticated(true);
   } catch (e) {
     if (e !== "No current user") {
       alert(e);
     }
   }
   dispatch(authentication({ type: "SET_AUTHING", payload: false }));
 }