最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is safe to insert 'dispatch' function as a dependency in useEffect function? - Stack Overflow

programmeradmin2浏览0评论

If I use this

  useEffect(() => {
dispatch(fetchToDos())}, [debouncedToDo, loginInfo.isLogin])

I get this warning

React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps

If I include 'dispatch' in dependency array the warning is gone.

Like this:

  useEffect(() => {
dispatch(fetchToDos())}, [dispatch, debouncedToDo, loginInfo.isLogin])

If I use this

  useEffect(() => {
dispatch(fetchToDos())}, [debouncedToDo, loginInfo.isLogin])

I get this warning

React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps

If I include 'dispatch' in dependency array the warning is gone.

Like this:

  useEffect(() => {
dispatch(fetchToDos())}, [dispatch, debouncedToDo, loginInfo.isLogin])
Share Improve this question edited Apr 8, 2021 at 21:53 Drew Reese 203k17 gold badges237 silver badges268 bronze badges asked Apr 8, 2021 at 21:38 George HutanuGeorge Hutanu 1601 silver badge7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 18

Yes, dispatch is safe to add to an useEffect hook's dependency array.

From the docs

INFO

The dispatch function reference will be stable as long as the same store instance is being passed to the <Provider>. Normally, that store instance never changes in an application.

However, the React hooks lint rules do not know that dispatch should be stable, and will warn that the dispatch variable should be added to dependency arrays for useEffect and useCallback. The simplest solution is to do just that:

export const Todos() = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchTodos())
  // Safe to add dispatch to the dependencies array
  }, [dispatch])
}
发布评论

评论列表(0)

  1. 暂无评论