0

The code

I have this simple <form> with both controlled and uncontrolled inputs.

(link to codesandbox.io)

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?

Afialapis
  • 83
  • 7
  • Following link has a very good explanation with code example https://daveceddia.com/useeffect-hook-examples/ – M.M.H.Masud Oct 19 '20 at 21:28
  • 1
    "Just because there is not an explicit `setValue` call?" Exactly. React components rerender when state or props update, and since neither are in the uncontrolled component there are no effects to re-trigger upon subsequent renders. – Drew Reese Oct 19 '20 at 21:29

0 Answers0