Search code examples
javascriptreactjsreduxreact-redux

ReactJs - best way to call redux action in useEffect


I have one component that fetch articles with axios, I want to retrieve the articles only in the first load of the url

useEffect( () => { 
    const getArticles = ()=>{
         dispatch(getArticlesAction())
   }   
    getArticles()
  }, [])

This way works perfectly, but I read some documentation I can have the same result with this:

useEffect( () => {    
    dispatch(getArticlesAction())
  }, [dispatch])

Using this also works without problems, I am passing the dispatch as dependency of useEffect, so my question is what is the best way to fetch the articles on the first load of the page? Thank you.


Solution

  • Both of these are technically pretty much equivalent. Technically you do not need to put dispatch into the dependency array as there is a good chance it will stay referentially equal for the lifetime of your application (unless you suddenly change out the store, which should not happen).

    You should be using eslint with the official react-eslint plugin though (you might need to enable the eslint plugin in your editor), and that will warn you that you need to add dispatch. Since it doesn't hurt to do so, I'd recommend to go with it.