Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use isomorphic useEffect depending on whether it's being run on the server or the client #260

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions packages/hooks/src/useLockScroll.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useLayoutEffect } from 'react'
import { useCallback, useLayoutEffect, useEffect } from 'react'

const getScrollbarSize = (): number => {
const tempDiv = document.createElement('div')
Expand Down Expand Up @@ -42,8 +42,12 @@ const setStyleProperty = (
}
}

export const useLockScroll = (element: HTMLElement = document.body): void => {
const useIsomorphicLayoutEffect =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like a useful stuff, can we put it in a separate file and export from package?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, will do.

As for the PR itself, I. guess it's okay to close it. Doesn't seem like a good solution, as we've discussed.

typeof window !== 'undefined' ? useLayoutEffect : useEffect

export const useLockScroll = (target?: HTMLElement): void => {
const lockScroll = useCallback(() => {
const element = target ?? document.body
if (!isVerticalScroll(element)) return

const previousValues = {
Expand All @@ -63,9 +67,9 @@ export const useLockScroll = (element: HTMLElement = document.body): void => {
}

return unlockScroll
}, [element])
}, [target])

useLayoutEffect(() => {
useIsomorphicLayoutEffect(() => {
const unlockScroll = lockScroll()
return unlockScroll
}, [lockScroll])
Expand Down