0

I have this simple React sample app (CodeSandbox):

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [someText, setSomeText] = useState<string>("");
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <input
        type="text"
        value={someText}
        onChange={(e) => {
          setSomeText(e.target.value);
          console.log(someText); // output 1
        }}
      />
      <button type="button" onClick={() => console.log(someText) // output 2 }> 
        Hit me!
      </button>
    </div>
  );
}

What I'm trying to understand is: "output 1" isn't is always one character compared to what I have typed into the textbox, while "output 2" is up to date when hitting the button.

How can I make sure someText is up to date after onChange - given I have more complex scenarios to handle in onChange?

Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124
  • *How can I make sure someText is up to date after onChange - given I have more complex scenarios to handle in onChange* --- In a case like this you have two options: continue to use `e.target.value` throughout the function, or move additional logic into a `useEffect` that depends on `someText`. – Brian Thompson Sep 21 '21 at 18:45
  • @BrianThompson Yes, the linked post solved it. And I noticed that I've already bookmarked it a while ago... – Alexander Zeitler Sep 22 '21 at 06:10

1 Answers1

1

Setting state does not happen at once. You may set the state in one line , but react will finish processing the whole onChange actions ( meaning it will do the console.log) and after that, it will try to render the updated state and you will have access to the updated state. So if you want the updated state here is how you can observe it. Add a useEffect hook and pass your state as the second dependency. Then do a console.log in there to see if the state is getting updated or not ( spoilers: it does of course)

useEffect(()=>{
console.log(someText)
},[someText])

what this piece of code does: whenever someText is updated , whatever is passed in useEffect , will be rendered.

Sobhan Jahanmard
  • 821
  • 5
  • 16