#Prevent unnecessary re-rendering

3 messages · Page 1 of 1 (latest)

marsh totem
#

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>
  )
}```
languid orchidBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

forest gyro