Home > Blockchain >  how do i create a custom hook that returns the key pressed as many times as it is pressed in react
how do i create a custom hook that returns the key pressed as many times as it is pressed in react

Time:01-11

I am trying to create a custom hook that returns the key pressed but when I press the same key more than twice it only returns twice

my code:

import { useEffect, useState } from "react"

function useKeyPressed() {
  const [key, setKey] = useState("")

  const handle = (e) => {
    setKey(e.key)
  }

  useEffect(() =>{
    document.addEventListener("keydown", handle)    
    return () => document.removeEventListener("keydown", handle)
  }, [])

  return key
}

I want the hook to return the key pressed as many times as it is pressed even if the same key is pressed many times

CodePudding user response:

By default, React doesn't rerender when a state update makes the state be the same (because usually you don't want to have a useless rerender), but if you want it to force a rerender when the same key is pressed you can have a separate state to just toggle whenever you want to force a rerender.

import { useEffect, useState } from "react"

function useKeyPressed() {
  const [key, setKey] = useState("")
  const [rerender, setRerender] = useState(false)

  const handle = (e) => {
    setKey(e.key)
    setRerender((prev) => !prev)
  }

  useEffect(() =>{
    document.addEventListener("keydown", handle)    
    return () => document.removeEventListener("keydown", handle)
  }, [])

  return key
}
  • Related