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>
);
}
CodePudding user response:
You've forgotten return before unmount callback
should be like so:
React.useEffect(() => {
window.addEventListener("keydown", keydown);
return () => {
window.removeEventListener("keydown", keydown);
};
}, [keydown]);
CodePudding user response:
You're adding an event listener every time a component mounts or updates. The useEffect hook is the wrong place to declare an event listener since the declared function is called at every update.
Maybe see the official docs on the useEffect hook?
