Created
November 1, 2018 10:05
-
-
Save gaearon/cb5add26336003ed8c0004c4ba820eae to your computer and use it in GitHub Desktop.
Examples from "Making Sense of React Hooks"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function MyResponsiveComponent() { | |
const width = useWindowWidth(); // Our custom Hook | |
return ( | |
<p>Window width is {width}</p> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useWindowWidth() { | |
const [width, setWidth] = useState(window.innerWidth); | |
useEffect(() => { | |
const handleResize = () => setWidth(window.innerWidth); | |
window.addEventListener('resize', handleResize); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
}; | |
}); | |
return width; | |
} |
Hi @gaearon, I'm very new to hooks, but isn't this typically the case where you would opt out from cleaning at each render in
useEffect
and rather have:useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, []); // <-- empty arrayAs suggested in the note from the docs, the empty array makes it so that the effect is run and cleaned up when the component mounts / unmounts.
Otherwise you would add and remove a window listener at each render, right?
I had same thought, I wonder why Dan uses his original example though (useEffect
without []
) - it can be slightly confusing. @gaearon
i am one of the newbie in react learning.
thank you for explanation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How would one go about testing these event listeners?