Last active
August 12, 2022 10:46
-
-
Save crutchcorn/4ec62c0e1653042ecc4e69e621e9272f to your computer and use it in GitHub Desktop.
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
const useWindowSize = () => { | |
// This doesn't handle resizes or SSR, only used for demos | |
const [height, setHeight] = useState(window.innerHeight); | |
const [width, setWidth] = useState(window.innerWidth); | |
return {height, width}; | |
} |
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
// ❌ Not allowed, the function name must start with `use` | |
const getWindowSize = () => { | |
const [height, setHeight] = useState(window.innerHeight); | |
const [width, setWidth] = useState(window.innerWidth); | |
return {height, width}; | |
} |
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
const useWindowSize = () => { | |
const [height, setHeight] = useState(window.innerHeight); | |
const [width, setWidth] = useState(window.innerWidth); | |
return {height, width}; | |
} | |
// ❌ Not allowed, you must use a hook _inside_ | |
// a component or another hook | |
const {height, width} = useWindowSize(); | |
const Component = () => { | |
return <p>Height is: {height}</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
const useWindowSize = () => { | |
// ❌ Not allowed, you cannot `return` before using a hook | |
if (bool) return {height: 0, width: 0} | |
const [height, setHeight] = useState(window.innerHeight); | |
let widthProps; | |
// ❌ Also not allowed, you can't use hooks inside of conditionals | |
if (bool) { | |
widthProps = useState(window.innerWidth); | |
} | |
return {height, widthProps}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment