D
D
dron1122021-05-06 07:49:31
React
dron112, 2021-05-06 07:49:31

Why pass dispatch to the useEffect hook?

Why is dispatch passed to the useEffect dependency array, what does it give?

const dispatch = useDispatch()

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sun_Day, 2021-05-06
@Sun_Day

Mostly to fix warnings from eslint. The same will happen if you write like this
useEffect(() => { вызов dispatch }, [])

The dispatch function reference will be stable as long as the same store instance is being passed to the . 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:

link to documentation
In general, lint rules don't know that you are referencing the same store instance. If the reference does not change, then a new call to useEffect should not occur. And therefore warns that the variable must be added to the dependency array.
Options:
1) Do what you have shown above.
2) Disable the linter rule in this particular place with the line // eslint-disable-line
3) Disable the rule globally in the eslint config itself. Google to the rescue.

M
Mikhail Osher, 2021-05-06
@miraage

eslint-plugin-react-hooksdoes not know that the given function does not change its reference.
Can be configured via advanced configuration .

{
  "rules": {
    // ...
    "react-hooks/exhaustive-deps": ["warn", {
      "additionalHooks": "useDispatch|useOtherHookWhichWillDefinitelyNotChange"
    }]
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question