React Hook useEffect has missing dependencies: 'myDate' and 'setMyDate'. Either include them or remove the dependency array.
How can missing dependencies be added to a useEffect that is run only once? The following example generates the warning above:
const [ myDate, setMyDate ] = useState(0)
const spinner = useRef(null)
useEffect( () => {
spinner.current = setInterval( () => {
d = Date.now()
if (d < myDate)
setUpdate(d)
}, 997 )
}, [])
If I include them, I create an infinite loop, as the setTimeout changes the values of the dependencies:
const spinner = useRef(null)
useEffect( () => {
spinner.current = setInterval( () => {
d = Date.now()
if (d < myDate)
setMyDate(d)
}, 997 )
}, [myDate, setMyDate])
If I remove the dependency array, the useEffect runs on each render, and sets up an infinite number of setIntervals:
const spinner = useRef(null)
useEffect( () => {
spinner.current = setInterval( () => {
d = Date.now()
if (d < myDate)
setMyDate(d)
}, 997 )
})
I also tried removing the useEffect entirely, thinking that since spinner is a useRef, it would not reassign on each component render... but no:
const spinner = useRef(null)
spinner.current = setInterval( () => {
d = Date.now()
if (d < myDate)
setMyDate(d)
}
Also tried using a functional update approach, like so, but lint error persist and the code doesn't work:
const spinner = useRef(null)
useEffect( () => {
spinner.current = setInterval( () => {
d = Date.now()
setMyDate(d => {
if (d < myDate)
setMyDate(d)
}
}, 997 )
}, [setMyDate])
I'm stuck... caught between a rock and a hard place! How can I resolve this lint warning?
The solution is to get
myDate(nameddatein my code just to be clear) from thesetMyDatefunction itself instead of passing it as a dependency.setMyDateis memoized and therefore doesn't need to be passed as a dependency.