1

Linter is complaining about a function that is missing as a dependency even though I am using the recommended useCallback hook in the parent component where it is defined.

Does anyone know how to fix this? Can't seem to find an example anywhere

link to sandbox here https://codesandbox.io/s/hopeful-wind-w4sp5

const arr = ['One', 'Two', 'Three']

const SyncingData = () => {
  const [progress, setProgress] = useState(0)

  const [children, setChildrenProgress] = useState(arr.map(item => 0))

  const handleChildrenProgress = useCallback(
    (progress, index) => {
      setChildrenProgress(
        children.map((item, currIndex) =>
          index === currIndex ? progress : item,
        ),
      )
    },
    [children],
  )

  useEffect(() => {
    setProgress(
      children.reduce((sum, item) => (sum = sum + item), 0) / children.length,
    )
  }, [children])

  return (
    <div>
      <div>Total Progress: {progress}</div>
      <ul>
        {arr.map((item, index) => (
          <Child
            key={index}
            index={index}
            updateProgress={handleChildrenProgress}
            name={item}
            delay={10 * index}
          />
        ))}
      </ul>
    </div>
  )
}

const Child = ({updateProgress, name, index, delay}) => {
  const [progress, setProgress] = useState(0)


  // This is the useEffect the linter doesn't like
  useEffect(() => {
    updateProgress(progress, index)
  }, [progress, index])

  useInterval(() => {
    if (progress < 100) {
      setProgress(progress + 1)
    }
  }, delay)

  return (
    <div>
      {name} {progress}
    </div>
  )
}

James
  • 157
  • 13

1 Answers1

0

I think you should try to add "updateProgress" in the list of dependencies of the effect :

useEffect(() => {
    updateProgress(progress, index)
  }, [progress, index, updateProgress])

the function updateProgress is enclosed in the lambda you provide to the effect.

The linter is trying to tell you that if that function changes, the effect will not take that change into account.

user2964630
  • 73
  • 1
  • 5
  • Thanks for your reply - I have tried this but i get maximum update depth error Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. – James Feb 28 '20 at 14:03