skip to Main Content

Is there any point in specifying a second argument to useEffect, such as a function that never changes?

useEffect(
  () => {
    const dispatch(asyncTestFunction({ data }))
  },
  [data, dispatch],
);

In this case, why do we put dispatch as the second argument?

The documentation states that it is not necessary to include functions such as useState.

https://ja.reactjs.org/docs/hooks-reference.html#usestate

2

Answers


  1. Those [data, dispatch] are called dependencies not arguments, which means your useEffect is dependent on them changing for it to be triggered.

    Leave the array [] empty, your useEffect will be called only when the page loads. In your case you can use only [data] so that when data changes your useEffect is triggered.

    You don’t need to add functions as dependencies because that may cause the useEffect to be called infinitely.

    Think of it like this "when data changes I want to dispatch" but if I say "when dispatch changes I wanna dispatch again". See how that can cause an infinite loop.

    Login or Signup to reply.
  2. Your implementation might be like this ,

    const dispatch = useDispatch();
    
    //Effect to dispatch action to redux store
    
    useEffect(
      () => {
         dispatch(asyncTestFunction({ data }))
      },
      [data, dispatch],
    );
    

    Here the linter(eslint) is satisfied as you are adding dispatch to deps array.
    The linter doesn’t know whether the dispatch reference will remain the same or change in subsequent renders, even though it is stable since the store was created.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search