React hooks value is not accessible in event listener function
Every render you get a new copy of resize
function. Each copy captures the current value of width
. Your listener has a copy which was created on the first render with width = 0
.
To fix this issue you have several options:
Update listeners when
width
changesuseEffect(() => { resize(); window.addEventListener("resize", resize); return () => window.removeEventListener("resize", resize); }, [width]);
Use functional updates to get the current width inside listener
const resize = () => { setWidth(oldWidth => { console.log("width:", oldWidth); return window.innerWidth }); };
Store the width in a mutable reference
const widthRef = useRef(width); const resize = () => { console.log("width:", widthRef.current); widthRef.current = window.innerWidth; setWidth(window.innerWidth); };