I have a very basic react ponent as you can see below. So as far as I know every time state value change, this ponents re-render. But the thing I want to know, if the ponent re-render every time I type something in input field, why input value stay the same and not going back to empty value?
import React, { useState } from "react";
const InputExample = () => {
const [value, setValue] = useState("");
console.log("render");
return (
<>
<input type="text" onChange={(e) => setValue(e.target.value)} />
</>
);
};
export default InputExample;
I have a very basic react ponent as you can see below. So as far as I know every time state value change, this ponents re-render. But the thing I want to know, if the ponent re-render every time I type something in input field, why input value stay the same and not going back to empty value?
import React, { useState } from "react";
const InputExample = () => {
const [value, setValue] = useState("");
console.log("render");
return (
<>
<input type="text" onChange={(e) => setValue(e.target.value)} />
</>
);
};
export default InputExample;
Share
Improve this question
asked Oct 6, 2021 at 15:25
Jantoma21Jantoma21
4956 silver badges13 bronze badges
2 Answers
Reset to default 6You are confusing re-rendering with reinitializing. Re-rendering just updates the DOM to reflect the changes in the state. It does not mean the ponent is recreated and assigned the initial state it began with.
In this case, whenever the input is changed, the value variable gets updated with what was entered in the input element.
Becuase value is not set, it is considered "uncontrolled" and does the default html behavior. In order to keep it as an empty value, you'd have to do something like:
import React, { useState } from "react";
const InputExample = () => {
const [value, setValue] = useState("");
console.log("render");
return (
<>
<input type="text" onChange={(e) => setValue(e.target.value)} value="" />
</>
);
};
export default InputExample;