The code
I have this simple <form>
with both controlled and uncontrolled inputs.
import React, { useState, useEffect, useRef } from "react";
const ControlledInput = () => {
const [value, setValue] = useState("controlled");
useEffect(() => {
console.log("Controlled: useEffect() cause value has changed to " + value);
}, [value]);
console.log("Controlled: re-render with " + value);
return (
<div>
<label>Controlled input</label>
<input
name={"controlled"}
value={value}
onChange={(ev) => setValue(ev.target.value)}
/>
</div>
);
};
const UncontrolledInput = () => {
const [value, _setValue] = useState("uncontrolled");
useEffect(() => {
console.log(
"Uncontrolled: useEffect() cause value has changed to " + value
);
}, [value]);
console.log("Uncontrolled: re-render with " + value);
return (
<div>
<label>Uncontrolled input</label>
<input name={"uncontrolled"} defaultValue={value} />
</div>
);
};
const App = () => {
return (
<form>
<ControlledInput />
<UncontrolledInput />
</form>
);
};
export default App;
What do I expect
To see console.log
messages after every change of input's values, both on controlled and uncontrolled inputs
What do I get
It happens just on controlled input, while not on the uncontrolled.
The question
I understand React handles uncontrolled inputs by its own. And, somehow, it avoids input to being re-rendered cause value
is handled internally. But... why is this useEffect
not running on further value
changes? Just because there is not an explicit setValue
call?
I'm interested in the real and good explanation of my previous incomplete assumption, but, most of all:
How can I make this useEffect
to actually run any time value
changes?