Home > Back-end >  How does input value stay same even though component re-render?
How does input value stay same even though component re-render?

Time:10-07

I have a very basic react component as you can see below. So as far as I know every time state value change, this components re-render. But the thing I want to know, if the component 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;

CodePudding user response:

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;

CodePudding user response:

You are confusing re-rendering with reinitializing. Re-rendering just updates the DOM to reflect the changes in the state. It does not mean the component 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.

  • Related