The missing dependency warning in React's useEffect hook occurs when you don't include all the values that your effect depends on in the dependency array. React uses this dependency array to know when to re-run the effect. If you don't list a value that is used inside the effect but not in the dependency array, React will warn you because it could lead to bugs or unexpected behavior due to stale or outdated values.
How to Fix the Warning
To fix the missing dependency warning, add all variables and props used inside the useEffect callback to the dependency array. This ensures that the effect is run every time one of those dependencies changes.
Code:
import { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count has changed to', count);
}, [count]); // `count` is now included as a dependency
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}