0

The question is, why when we type "1" in textarea console.log shows empty string, but actually textInput = "1"?

const [textInput, setTextInput] = useState('')

const inputAction= (e) => {
   setTextInput(e.target.value);
   console.log(textInput);
};

<textarea
value={textInput}
onChange={inputAction}
></textarea>
Rurohi53
  • 122
  • 1
  • 8
  • 1
    The answer is "closures". Your state variable is block scoped to the current render, therefore it doesn't reflect the new value until it is redeclared on the next render. – Cal Irvine Dec 02 '21 at 16:42

1 Answers1

-1

setTextInput does not immediately update the value of textInput - instead, it queues a re-render, and during that render the value will be updated. This is a pretty common React question, I'd encourage you to read up on State and Lifecycle to get a better sense for what's going on here.

Donut
  • 110,061
  • 20
  • 134
  • 146