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

155
Views
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>
  );
}



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

0

You've forgotten return before unmount callback

should be like so:

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

    return () => {
      window.removeEventListener("keydown", keydown);
    };
  }, [keydown]);
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!