This is an onscreen keyboard component.
I don't feel like rewriting all the properties for a single key button every time because that would make the code look ugly, so I opted for an extra component that I treat as a "key button shorthand", problem is every time I press a key I notice the rest of the keys also rerender because of the state change, what's an alternative solution to prevent this?
let keyInterval = useRef<NodeJS.Timeout>()
let keyTimeout = useRef<NodeJS.Timeout>()
function keyDownBehaviour(action: () => void) {
action()
keyTimeout.current = setTimeout(() => {
keyInterval.current = setInterval(() => {
action()
}, 50)
}, 500)
}
function keyUpBehaviour() {
clearInterval(keyInterval.current)
clearTimeout(keyTimeout.current)
}
function Key({ text }: { text: string }) {
return (
<Button
className="text-lg p-0 w-12"
variant="outline"
onMouseDown={() => keyDownBehaviour(() => setState(prevAnswer => prevAnswer + text))}
onMouseUp={keyUpBehaviour}
onMouseLeave={keyUpBehaviour}
>
{text}
</Button>
)
}
return (
<div className="flex flex-col mt-2 gap-2 w-auto">
<div className="flex gap-[0.2rem] sm:gap-2 w-auto">
<Key text="b" />
<Key text="a" />
</div>
</div>
)
}```