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

140
Vistas
Listen for Change ONLY ONCE on a React Controlled Input

I am attempting to emit a socket event on user input but I want the event to be emitted ONLY ONCE when the value of the input changes in state and another event to be emitted ONCE when the value is cleared.

const [text, setText] = useState("");

...

useEffect(()=> {
      if (text) {
        // EMIT EVENT
        console.log("input has value emit event", text);
      } else {
        console.log("input has no value emit event");
      }
}, [text]);

...

const handleChange = e => {
    setText(e.target.value);
}

...

<Input type="text" value={text} onChange={handleChange} />

I am able to accomplish this but my code emits on every keystroke. My requirement is for both events to emit only once.

  • One when there is a value in state
  • Another when there is no value in state
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Do the check in handleChange instead, so that you can compare the prior value to the new value.

const handleChange = e => {
    const newText = e.target.value;
    setText(newText);
    if (newText && !text) {
        console.log("input has value emit event", text);
    } else if (!newText && text) {
        console.log("input has no value emit event");
    }
}
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