I have a queryTerm
variable as a dependency to a useEffect
hook. I also register a handleKeyPress
event listener in the same hook.
I am facing an issue whereby when the queryTerm
dependency changes, the queryTerm
value in the handleKeyPress
listener is always one step behind the new queryTerm
value.
How would I go about synchronising the two?
import React, { useState, useEffect } from 'react'
const Test = () => {
const [queryTerm, setQueryTerm] = useState('')
const handleChange = (event) => {
setQueryTerm(event.target.value)
}
useEffect(() => {
console.log({ outside: queryTerm })
const handleKeyPress = (event) => console.log({ inside: queryTerm })
window.addEventListener('keydown', handleKeyPress)
return () => window.removeEventListener('keydown', handleKeyPress)
}, [queryTerm])
return (
<div className='App'>
<input onChange={handleChange} />
</div>
)
}
export default Test