Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

setTitle asyncronous, you must check title changes in useEffect

useEffect(() => {
   console.log(title);
}, [title])
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda