简体   繁体   中英

addEventListener does not work within a useEffect hook

The following is a component whose functionality, partly, is to change the window's title as the page is getting focused and blurred. It does not work.

const ATitleChangingComponent = () => {

    const focusFunction = (event: FocusEvent) => {
            document.title = "focused";
    };
    const blurFunction = (event: FocusEvent) => {
            document.title = "blurred";
    };


    useEffect(() => {
            window.addEventListener("focus", focusFunction);
            return window.removeEventListener("focus", focusFunction);
    }, []);

    useEffect(() => {
            window.addEventListener("blur", blurFunction);
            return window.removeEventListener("blur", blurFunction);
    }, []);

    return <p>some unimportant jsx</p>
};

However,

const focusFunction = (event: FocusEvent) => {
    document.title = "focused";
}; 
window.addEventListener("focus", focusFunction);

works just fine.

A side question: are const focusFunction and const blurFunction getting constructed within the function each render? I assume if so, they should be lifted out of the component to avoid unnecessary overhead?

Need to return a function, otherwise listener is removed immediately.

The function gets called when the component unmounts

useEffect(() => {
        window.addEventListener("blur", blurFunction);
        return () => window.removeEventListener("blur", blurFunction);
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM