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 hidden or 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 hidden or 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; | |
} |
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
I had same thought, I wonder why Dan uses his original example though (
useEffect
without[]
) - it can be slightly confusing. @gaearon