Skip to content

Instantly share code, notes, and snippets.

@crutchcorn
Last active August 12, 2022 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crutchcorn/4ec62c0e1653042ecc4e69e621e9272f to your computer and use it in GitHub Desktop.
Save crutchcorn/4ec62c0e1653042ecc4e69e621e9272f to your computer and use it in GitHub Desktop.
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};
}
// ❌ 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};
}
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>
}
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