Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading