1

In my useEffect code I am dispatching an action which are fetched from the slice.

But then it throws error "React Hook useEffect has missing dependencies" as inside the hooks I am using actions and dispatch

...
const { actions } = useDataListSlice();
....
useEffect(() => {
  dispatch(actions.loadInitialState());
}, []);

I can add actions and dispatch to dependency array but I am not sure if its right to add actions and dispatch in it

raja pateriya
  • 332
  • 2
  • 15
  • https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook This question in depth describes your problem – Simas.B Jun 15 '21 at 11:59
  • @Simas.B stackoverflow.com/questions/55840294/ this discusses about custom function in useEffect, but dispatch is a function from library so how that should be handled not discussed in that link. – Vivek Bani Jun 15 '21 at 12:04

2 Answers2

-1

Do you mean warning or error? If it is warning just add dispatch in your dependencies like this

useeffect(()=>{
 // dispatch something
},[dispatch])

If you think that warning will not break your application then you can leave the dependance empty and add // eslint-disable-next-line

Nick
  • 103
  • 9
-1

Here's a more in depth read here, https://github.com/facebook/create-react-app/issues/6880#issuecomment-485912528. Long story short, it comes to developer to decide what dependencies should be added to dependency array and what not, based on what functionality you're expecting, tools like eslint won't be able to 100% accurately show errors in your code, however it can get to your attention parts of code, that maybe you should inspect more carefully. To answer your own question, ask yourself when you want your React.useEffect to be called, what dependencies can change, and do you need your React.useEffect to be called on those changes. Not adding correct correct dependencies to dependency array might lead to bugs where hook wouldn't be called when needed, but also adding all dependencies used in React.useEffect to dependency array might lead to bugs where hook is called when it shouldn't be called.

In this particular scenario, asks yourself when does initial state need to be loaded:

  • only on component mount? leave dependency array empty;
  • when actions or dispatch changes? add required actions to dependency array.
Simas.B
  • 724
  • 1
  • 13
  • 31