Search code examples
javascriptreactjsreact-component

How does input value stay same even though component re-render?


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;

Solution

  • 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.