Skip to content

Instantly share code, notes, and snippets.

@Tim-W-James
Created February 12, 2023 06:52
Show Gist options
  • Select an option

  • Save Tim-W-James/ee22239cc7d657045c5579bfa0910809 to your computer and use it in GitHub Desktop.

Select an option

Save Tim-W-James/ee22239cc7d657045c5579bfa0910809 to your computer and use it in GitHub Desktop.
React useLockBodyScroll Custom Hook #hooks
const useLockBodyScroll = (): void => {
// useLaoutEffect callback return type is "() => void" type
useLayoutEffect((): (() => void) => {
// Get original body overflow
const originalStyle: string = window.getComputedStyle(
document.body
).overflow;
// Prevent scrolling on mount
document.body.style.overflow = "hidden";
// Re-enable scrolling when component unmounts
return () => (document.body.style.overflow = originalStyle);
}, []); // Empty array ensures effect is only run on mount and unmount
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment