Reputation: 61
so here is my code:
import { useState } from 'react'
function App() {
const [key, setKey] = useState()
document.addEventListener('keydown', (e) => {
setKey(e.key)
})
return (
<>
<div>{key}</div>
{console.log('hello world')}
</>
);
}
export default App;
when i press any key on a keyboard, it should setKey as whatever key i pressed and log 'hello world' in the console.. setting key part is working fine but logging part is what i don't get.. since console.log is outside of eventListener it shouldn't be effected by the eventListener but whenever i press a key, it logs 'hello world' in the console.. i would appreciate if someone help me out on this..
Upvotes: 0
Views: 587
Reputation: 1440
In react , whenever the State Updates the Component will rerender..
So Your Console.log was also rendered while you pressing the Key.
Upvotes: 1