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

React array not updating properly

I am experiencing a very weird bug in a basically fresh react project. I am attempting to update an array whenever the browser receives a keypress event. For some reason the update that I would expect to work is only editing the last value of the array or keeping it at a fixed length of 1.

function Component() {
  const [keypresses, setKeypresses] = useState([]);
  
  function updateKeypresses(e) {
   setKeypresses([...keypresses, e.keyCode]);
  }

  useEffect(() => {
    window.addEventListeneder('keydown', updateKeypresses);
    return () => {
      document.removeEventListener('keydown', updateKeypresses); 
    }  
  }, []);

  useEffect(() => {
    console.log(keypresses);
  }, [keypresses])
}
Output: I dont have codes memorized so image nums

press a
~> [a]
press b
~> [b]
press c
~> [c]

What I would expect:
~> [a]
~> [a,b]
~> [a,b,c]

>Solution :

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

The reason that the keypresses array always reset it because your pointer of the updateKeypresses function isn’t changed.
to fix it you have to add the keypresses state to the dependecies array of useEffect:

useEffect(() => {
    window.addEventListener('keydown', updateKeypresses);
    return () => {
      document.removeEventListener('keydown', updateKeypresses);
    };
  }, [keypresses]);
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