mason
mason

Reputation: 424

React Hook useEffect has a missing dependency: 'reduxArray'. Either include it or remove the dependency array

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 ?

Upvotes: 0

Views: 70

Answers (4)

mason
mason

Reputation: 424

Solved it by simply keeping a flag right after updating the redux array, I am not sure if it is the right approach,

useEffect(()=>{
     const filteredData = reduxArray.filter(
       () => // do something
     );
if(!flag) {
     store.dispatch(method({reduxArray:[...filteredData]}))
 }
  setFlag(true); // so that it doesn't reupdate infinite times
  },[data])

Upvotes: 0

Hasan Aga
Hasan Aga

Reputation: 784

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])

Upvotes: 0

Uriel Cisneros
Uriel Cisneros

Reputation: 126

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])

Upvotes: 0

Muhammad Raheel
Muhammad Raheel

Reputation: 818

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])

Upvotes: 1

Related Questions