Prevent unnecessary re-rendering
Unanswered
Yellow and black potter wasp posted this in #help-forum
Yellow and black potter waspOP
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?
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?
function Keyboard({ setState }: { setState: React.Dispatch<React.SetStateAction<string>> }) {
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>
)
}2 Replies
https://react.dev/reference/react/useDeferredValue
maybe this would help?
maybe this would help?
@Ray https://react.dev/reference/react/useDeferredValue
maybe this would help?
Yellow and black potter waspOP
Can't see how it would