Skip to content

Instantly share code, notes, and snippets.

@tthew
Created February 28, 2020 20:40
Show Gist options
  • Select an option

  • Save tthew/bdd8890144bca7a0277e8c4ee5584b83 to your computer and use it in GitHub Desktop.

Select an option

Save tthew/bdd8890144bca7a0277e8c4ee5584b83 to your computer and use it in GitHub Desktop.
const useWindowResize = invokeImmediately => {
const [immediatelyInvoked, setImmediatelyInvoked] = useState(false);
const [rect, setRect] = useState({
innerWidth: undefined,
innerHeight: undefined
});
const set = useCallback(() => {
if (!window) return;
const { innerWidth, innerHeight } = window;
setRect({ innerWidth, innerHeight });
}, []);
useEffect(() => {
window.addEventListener("resize", set);
return () => {
window.removeEventListener("resize", set);
};
}, [set]);
if (invokeImmediately && !immediatelyInvoked) {
set();
setImmediatelyInvoked(true);
}
return rect;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment