简体   繁体   中英

Understanding Exhaustive deps ESlint warning with n useEffect

Cant seem to get my head around the right approach for this. Want to get ride of the warning and not by having the inline ignore warning comment. Probably useCallback is in the direction of the solution. I just want to check only once when functional component gets initialised wether if the Store needs, conditionally. Thats all.

Line 72:6: React Hook useEffect has missing dependencies: 'dispatch' and 'storedSlugItems'. Either include them or remove the dependency array react-hooks/exhaustive-deps

useEffect(() => {
  if (storedSlugItems.length > 0) {
    dispatch(setSlugItems(storedSlugItems));
  }
  // eslint-disable-next-line 
}, []);

Just add dispatch to useEffect dependencies:

useEffect(() => {
  if (storedSlugItems.length > 0) {
    dispatch(setSlugItems(storedSlugItems));
  }
}, [dispatch]);

It probably also matters what dispatch is and where it comes from, but adding it to the dependencies should work.

If it is Redux 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 - to add it to the dependencies:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM