This warning means that I have not included all the variables I use in the
Let's take a look at the different variations of the
The
useEffect(() => {
console.log("some text") //executes in every component re-render
})
That may not be necessary and may negatively impact performance.
I can control the
useEffect(() => {
console.log("some text") //executes only when the component initially mounts
},[])
Now, what if I use a state variable inside the
useEffect(() => {
if(text){
console.log(text)
}
}, [])//React Hook useEffect has a missing dependency warning
I can overcome this limitation by including the text variable in the dependency array. In that way, my
import { useEffect, useState } from "react";
const App = () => {
const [text, setText] = useState<string>("")
useEffect(() => {
if(text){
console.log(text)//runs when text changes
}
}, [text])
return (
<div>
<textarea onChange={(e) => setText(e.target.value)}></textarea>
</div>
);
}
export default App;
The same rules apply when I use props inside my
In the below code, the
useEffect(() => {
if(props.text){
console.log(props.text)
}
}, []) //React Hook useEffect has a missing dependency warning
I can solve that potential issue by adding the
useEffect(() => {
if(props.text){
console.log(props.text)
}
}, [props.text])