Home > OS >  React Hook useEffect has a missing dependency: 'reduxArray'. Either include it or remove t
React Hook useEffect has a missing dependency: 'reduxArray'. Either include it or remove t

Time:09-16

I need to call useEffect when ever data changes like below,

 useEffect(()=>{
     const filteredData = reduxArray.filter(
       () => // do something
 );
     store.dispatch(method({reduxArray:[...filteredData]}))
  },[data])

this actually meets my requirement and works fine for me but Eslint is not happy with the same and gives me the error React Hook useEffect has a missing dependency: 'reduxArray'. Either include it or remove the dependency array.

In that case if I add reduxArray in the dependency array then it causes infinite loop in the useEffect since I am updating reduxArray in the useEffect. Is there a way other than disabling eslint to overcome this ?

CodePudding user response:

I don't know if it's a good solution are not but if you want to remove eslint warning then just use

  useEffect(()=>{
   const filteredData = reduxArray.filter(() => // do something);
   store.dispatch(method({reduxArray:[...filteredData]}))
   // eslint-disable-next-line react-hooks/exhaustive-deps
  },[data])

CodePudding user response:

A solution that I like for this is to use the useCallback in a function, this will prevent an infinite loop.

const handleChangeData = useCallback (() => {
    const filteredData = reduxArray.filter();
    store.dispatch(method({reduxArray:[...filteredData]}))
  },[data,reduxArray])

  useEffect(()=>{
    handleChangeData
 },[handleChangeData])

CodePudding user response:

One solution to this problem is the useEvent hook:

  const filterData = useEvent(()=>{
    const filteredData = reduxArray.filter(
      () => // do something
);
    store.dispatch(method({reduxArray:[...filteredData]}))
  })

  useEffect(()=>{
    filterData()
 },[data])
  • Related