refactor: use more react-use

This commit is contained in:
EnixCoda 2020-03-15 02:38:07 +08:00
parent e3ffc8f82b
commit 1a91bdc2e9
No known key found for this signature in database
GPG key ID: 0C1A07377913A1DD
4 changed files with 8 additions and 35 deletions

View file

@ -1,11 +1,11 @@
import { HorizontalResizeHandler } from 'components/ResizeHandler'
import { useConfigs } from 'containers/ConfigsContext'
import * as React from 'react'
import { useWindowSize } from 'react-use'
import { cx } from 'utils/cx'
import { bodySpacingClassName } from 'utils/DOMHelper'
import * as features from 'utils/features'
import { useMediaStyleSheet } from 'utils/hooks/useMediaStyleSheet'
import { useWindowSize } from 'utils/hooks/useWindowSize'
export type Size = number
type Props = {
@ -24,13 +24,11 @@ export function Resizable({ baseSize, className, children }: React.PropsWithChil
setSize(baseSize)
}, [baseSize])
useWindowSize(
width => {
if (size > width - MINIMAL_CONTENT_VIEWPORT_WIDTH)
setSize(width - MINIMAL_CONTENT_VIEWPORT_WIDTH)
},
[size],
)
const { width } = useWindowSize()
React.useEffect(() => {
if (size > width - MINIMAL_CONTENT_VIEWPORT_WIDTH)
setSize(width - MINIMAL_CONTENT_VIEWPORT_WIDTH)
}, [width, size])
React.useEffect(() => {
document.documentElement.style.setProperty('--gitako-width', size + 'px')

View file

@ -11,11 +11,10 @@ import { SideBarCore } from 'driver/core'
import { ConnectorState, Props } from 'driver/core/SideBar'
import { oauth } from 'env'
import * as React from 'react'
import { useEvent } from 'react-use'
import { useEvent, useUpdateEffect } from 'react-use'
import { cx } from 'utils/cx'
import * as DOMHelper from 'utils/DOMHelper'
import { JSONRequest, parseURLSearch } from 'utils/general'
import { useDidUpdate } from 'utils/hooks/useDidUpdate'
import * as keyHelper from 'utils/keyHelper'
import * as URLHelper from 'utils/URLHelper'
@ -83,7 +82,7 @@ const RawGitako: React.FC<Props & ConnectorState> = function RawGitako(props) {
useEvent('pjax:complete', attachCopySnippetButton, window)
// init again when setting new accessToken
useDidUpdate(() => {
useUpdateEffect(() => {
props.init()
}, [accessToken || '']) // fallback for preventing duplicated requests

View file

@ -1,12 +0,0 @@
import * as React from 'react'
export function useDidUpdate(effect: React.EffectCallback, deps?: React.DependencyList) {
const firstTime = React.useRef(true)
React.useEffect(() => {
if (firstTime.current) {
firstTime.current = false
return
}
return effect()
}, deps)
}

View file

@ -1,12 +0,0 @@
import * as React from 'react'
export function useWindowSize(
callback: (width: number) => void,
deps?: ReadonlyArray<any> | undefined,
) {
React.useEffect(() => {
const resizeListener: (this: Window, ev: UIEvent) => void = () => callback(window.innerWidth)
window.addEventListener('resize', resizeListener)
return () => window.removeEventListener('resize', resizeListener)
}, deps)
}