How to make 'document.addEventListener' in React fire after state changes?

Viewed 40

This is my code. The addEventLister will always fire before state is updated. Therefore, console.log(state) will be the previous state. How can I make it fire after the state updated? I thought addEventListener is supposed to fire after attribute event. Why is it different for this case?

export const MyComponent = () {
  const [state, setState] = useState();
          
  useEffect( () => {
    const handleClick = e => { console.log(state) }

    document.addEventListener("mousedown", handleClick)

    return () => {
      // Cleanup the event listener
      document.removeEventListener("mousedown", handleClick)
    }

  }, [state]);
  
const myFunction = () => {  setState(1)  }
   
return (
  <div onClick={myFunction}>Button</div>


)


}
0 Answers
Related