Based on this popular answer https://stackoverflow.com/a/19014495 I have the following code.
I am trying to understand why "remove effect" is never logged.
function useWindowSize(){
const [size, setSize] = useState([0,0]);
useLayoutEffect(() => {
console.log("use effect");
function updateSize(){
setSize([window.innerWidth, window.innerHeight]);
}
window.addEventListener('resize', updateSize);
updateSize();
return () => {
console.log("remove effect");
window.removeEventListener('resize', updateSize);
}
}, []);
return size;
}
This custom hook is used in a function component
function InfiniteScroll () {
const [width, height] = useWindowSize();
// rest of code should be irrelevant
}
Based on the React documentation an empty array as second argument for the built in hooks means that the effect is used and then cleaned up only once. https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects. I was surprised therefore that this is used in this code snippet because the event listener would be removed immediately. However in testing I discovered that whilst "use effect" is logged "remove effect"is not. Why? What other concept am I missing?