The most common cause of the
Let's look at a few possible scenarios where this error can occur.
Take a look at the code listed below. Here is the typical life cycle the component goes through to generate the error.
As you can see, the above cycle continues. React Js detect this and issues the error message. That is an error, not a warning.
import { useState } from "react"
export const App = () => {
const [message, setMessage] = useState<string>()
//This will cause an infinite loop
setMessage("Enter your message")
return(
<>
<div>Name: <input value={message}/></div>
<div><button>Update</button></div>
</>
)
}
export default App
Set the default state variable value when the variable is initialized.
Handle the state change inside the
useEffect(() => {
setMessage("Enter your message")
},[])
Event handlers should be functions or function references. If I use a function call as an event handler, React will execute that function upon the component render.
In the below example, I use
import { useState } from "react"
export const App = () => {
const [message, setMessage] = useState("Enter your message")
return(
<>
<div>Name: <input value={message} onChange={(e) => setMessage(e.target.value)}/></div>
<div><button onClick={setMessage("")}>Reset</button></div>
</>
)
}
export default App
The solution is to pass a function to the onClick method.
Below is another example where I use a method call instead of a function or a function reference. Note that I do a state update within the
import { useState } from "react"
export const App = () => {
const [message, setMessage] = useState("Enter your message")
const resetMessage = () => {
setMessage("")
}
return(
<>
<div>Name: <input value={message} onChange={(e) => setMessage(e.target.value)}/></div>
<div><button onClick={resetMessage()}>Reset</button></div>
</>
)
}
export default App
The solution is to pass a function to the