Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
Why React returns empty when calling a function for the first time?

When I enter the first character in the input element I get "empty string".

function form(props) {
    // function getData(e){
    //     e.preventDefault()
    //     console.log(e.target[1].value)
    const [title, setTitle] = useState("")

    function getTitle(e){
        setTitle(e.target.value)
        console.log(title) //First time shows "empty string"
    }

    
    return (
        <form >
            <div>
                <label >Title</label>
                <input type="text"  name="title" onChange={getTitle} />
            </div>
    </form>)

The way I see it, I enter a character in the input element, "onChange" event is fired, the function getTitle is run, its sets the "title" variable, which is hooked to the useState hook, and next I console the result. Following this reasoning I expect to get the first character entered. Instead I get "empty string". From the second character onwards the console prints the characters.

With "onInput" function happens the same.

How to solve this and why happens?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Setting state is asynchronous, so your console.log is running before the state is set. If you use a useEffect hook to view the state, you should see the value. The useEffect hook runs post-render, so you will see your updated state information at that time.

useEffect(() => {
   console.log(title);
}, [title]);
about 4 years ago · Juan Pablo Isaza Report

0

setTitle asyncronous, you must check title changes in useEffect

useEffect(() => {
   console.log(title);
}, [title])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!