Skip to content

Instantly share code, notes, and snippets.

@ryanrabello
Forked from gaearon/MyResponsiveComponent.js
Created August 16, 2019 03:48
Show Gist options
  • Save ryanrabello/18a304e65839a06d89039b711584b53d to your computer and use it in GitHub Desktop.
Save ryanrabello/18a304e65839a06d89039b711584b53d to your computer and use it in GitHub Desktop.
Examples from "Making Sense of React Hooks"
function MyResponsiveComponent() {
const width = useWindowWidth(); // Our custom Hook
return (
<p>Window width is {width}</p>
);
}
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment