A
A
Arthur2020-05-13 00:35:53
React
Arthur, 2020-05-13 00:35:53

Why pass dispatch to hook dependencies?

Why pass dispatch to hook dependencies?

For example, I often see the use of the useEffect hook, in whose dependencies dispatch
[arg1, arg2, dispatch] is specified, why is this done?

And is it possible to use a function in useEffect in which something is dispatched, but create the dispatch inside the function? Or is it more correct to pass it as an argument to this function?
For example:

someFunc () {
  const dispatch = useDispatch()
  dispatch(something)
}

useEffect(someFunc, [])
...


или же делать 
someFunc (dispatch) {
  dispatch(something)
}
useEffect(() => someFunc(dispatch), [dispatch])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philbot, 2020-05-13
@philbot

For example, you need to pass information to the state after useEffect is executed, or after the component is unmounted.
In this case, you can

useEffect(() => {
    let isSubscribed = true;

    getDataFetch().then((res: any) => {
      const { result, error } = res;

      if (isSubscribed) {
        getRes({
          data: result || [],
          isLoaded: true,
          error,
        });
      }
    });

    return () => {
      dispatch(universalAction("SAVE", filterData));
      isSubscribed = false;
    };
  }, [dispatch, filterData])

Where dispatch is a redux hook
universalAction - your custom action that changes the information in the state
filterData - some kind of variable
Thus, the dispatch itself and the information in the filterData variable will be specified depending on the hook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question