Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

57
Vistas
Can't stop onkeypress firing exponentially

Every time I press a key, keydown event fires double the amount of times it did before, created a minimal example here https://codesandbox.io/s/epic-goldstine-sy852. I know I can remove amount from the callbacks dependencies but I am doing a lot of operations when a key is pressed and reusing them through-out my app, where amount can come from useState, useReducer or else where.

export default function App() {
  const [amount, updateAmount] = React.useState(0);

  return (
    <div className="App">
      <Text disableDecimal={true} amount={amount} updateAmount={updateAmount} />
    </div>
  );
}

export default function Text({ amount, updateAmount }) {
  const keydown = React.useCallback(
    ({ repeat, key }) => {
      if (repeat) return;
      console.log(key);
      if (!Number.isNaN(key)) updateAmount(parseFloat(amount.toString() + key));
    },
    [amount, updateAmount]
  );

  React.useEffect(() => {
    window.addEventListener("keydown", keydown);

    () => {
      window.removeEventListener("keydown", keydown);
    };
  }, [keydown]);

  return (
    <div>
      <h1>{amount}</h1>
    </div>
  );
}



7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You've forgotten return before unmount callback

should be like so:

  React.useEffect(() => {
    window.addEventListener("keydown", keydown);

    return () => {
      window.removeEventListener("keydown", keydown);
    };
  }, [keydown]);
7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.