Skip to content

Commit

Permalink
perf: Use callback for handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
memoyil committed Jun 29, 2024
1 parent 01219b2 commit 2822d2a
Show file tree
Hide file tree
Showing 113 changed files with 1,107 additions and 793 deletions.
6 changes: 3 additions & 3 deletions apps/web/src/components/AccessRisk/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { useQuery } from '@tanstack/react-query'
import AccessRiskTooltips from 'components/AccessRisk/AccessRiskTooltips'
import { ACCESS_TOKEN_SUPPORT_CHAIN_IDS } from 'components/AccessRisk/config/supportedChains'
import { fetchRiskToken } from 'components/AccessRisk/utils/fetchTokenRisk'
import { useEffect, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useAllLists } from 'state/lists/hooks'
import { useUserTokenRisk } from 'state/user/hooks/useUserTokenRisk'
import { styled } from 'styled-components'
Expand Down Expand Up @@ -56,12 +56,12 @@ function RetryRisk({ onClick }: { onClick: () => void }) {
const [retry, setRetry] = useState(false)
const { t } = useTranslation()
const [isTooltipDisplayed, setIsTooltipDisplayed] = useState(false)
const displayTooltip = () => {
const displayTooltip = useCallback(() => {
setIsTooltipDisplayed(true)
setTimeout(() => {
setIsTooltipDisplayed(false)
}, 1000)
}
}, [setIsTooltipDisplayed])
const retryTooltip = useTooltip(
<>
{t('Risk scanning failed.')} {!retry && t('Press the button to retry.')}
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/components/AddressInputSelect/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChangeEvent, useState, useEffect } from 'react'
import { ChangeEvent, useState, useEffect, useCallback } from 'react'
import { Box, BoxProps, Text, Input } from '@pancakeswap/uikit'
import { styled } from 'styled-components'
import { isAddress } from 'viem'
Expand Down Expand Up @@ -74,10 +74,10 @@ const AddressInputSelect: React.FC<React.PropsWithChildren<AddressInputSelectPro
}))
}

const handleClick = () => {
const handleClick = useCallback(() => {
setState(initialState)
onAddressClick(state.value)
}
}, [setState, onAddressClick, state.value])

// When we have a valid address fetch the data
useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,18 +114,18 @@ const AnniversaryAchievementModal: React.FC<AnniversaryModalProps> = ({ excludeL
closeOnceAnniversaryModal()
}, [closeOnceAnniversaryModal])

const handleClick = async () => {
const handleClick = useCallback(async () => {
setIsLoading(true)

try {
const receipt =
account &&
(await fetchWithCatchTxError(() =>
contract.write.claimAnniversaryPoints({
(await fetchWithCatchTxError(() => {
return contract.write.claimAnniversaryPoints({
account,
chain: contract.chain,
}),
))
})
}))

if (receipt?.status) {
toastSuccess(t('Success!'), <ToastDescriptionWithTx txHash={receipt.transactionHash} />)
Expand All @@ -141,7 +141,7 @@ const AnniversaryAchievementModal: React.FC<AnniversaryModalProps> = ({ excludeL
setShow(false)
setIsLoading(false)
}
}
}, [account, contract, router, t, closeOnceAnniversaryModal, fetchWithCatchTxError, toastError, toastSuccess])

return (
<ModalV2 isOpen={show} onDismiss={handleCloseModal} closeOnOverlayClick>
Expand Down
66 changes: 42 additions & 24 deletions apps/web/src/components/GlobalCheckClaimStatus/V3AirdropModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import useCatchTxError from 'hooks/useCatchTxError'
import { useV3AirdropContract } from 'hooks/useContract'
import { useShowOnceAirdropModal } from 'hooks/useShowOnceAirdropModal'
import delay from 'lodash/delay'
import { useEffect, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { styled } from 'styled-components'
import { useAccount } from 'wagmi'
import useAirdropModalStatus from './hooks/useAirdropModalStatus'
Expand Down Expand Up @@ -91,15 +91,16 @@ const V3AirdropModal: React.FC = () => {
}
}, [account, shouldShowModal, showOnceAirdropModal, v3WhitelistAddress])

const handleCloseModal = () => {
const handleCloseModal = useCallback(() => {
if (showOnceAirdropModal) {
setShowOnceAirdropModal(!showOnceAirdropModal)
setShowOnceAirdropModal((prevState) => !prevState)
}
setShow(false)
}
}, [showOnceAirdropModal, setShow, setShowOnceAirdropModal])

const handleClick = async () => {
const handleClick = useCallback(async () => {
setIsLoading(true)

try {
let v3ForSCResponse = v3ForSC
if (!v3ForSCResponse) {
Expand All @@ -111,7 +112,8 @@ const V3AirdropModal: React.FC = () => {
})
?.setData(v3ForSCResponse)
}
const { cakeAmountInWei, nft1, nft2 } = (account && v3ForSCResponse?.[account?.toLowerCase()]) || {}

const { cakeAmountInWei, nft1, nft2 } = (account && v3ForSCResponse?.[account.toLowerCase()]) || {}
let v3MerkleProofsResponse = v3MerkleProofs as { merkleProofs: { [account: string]: any } }
if (!v3MerkleProofsResponse) {
v3MerkleProofsResponse = await (await fetch(`${GITHUB_ENDPOINT}/v3MerkleProofs.json`)).json()
Expand All @@ -121,24 +123,26 @@ const V3AirdropModal: React.FC = () => {
queryKey: ['/airdrop-Merkle-json'],
})
?.setData(v3MerkleProofsResponse)
const proof = account ? v3MerkleProofsResponse?.merkleProofs?.[account?.toLowerCase()] || {} : {}
const receipt = v3AirdropContract.account
? await fetchWithCatchTxError(() =>
v3AirdropContract.write.claim([cakeAmountInWei, nft1, nft2, proof], {
account: v3AirdropContract.account!,
chain: v3AirdropContract.chain,
}),
)
: undefined
if (receipt?.status) {
if (showOnceAirdropModal) {
setShowOnceAirdropModal(!showOnceAirdropModal)
}
queryClient.invalidateQueries({
queryKey: [account, '/airdrop-claimed'],
})
toastSuccess(t('Success!'), <ToastDescriptionWithTx txHash={receipt.transactionHash} />)
}

const proof = account ? v3MerkleProofsResponse?.merkleProofs?.[account.toLowerCase()] || {} : {}
const receipt = v3AirdropContract.account
? await fetchWithCatchTxError(() =>
v3AirdropContract.write.claim([cakeAmountInWei, nft1, nft2, proof], {
account: v3AirdropContract.account!,
chain: v3AirdropContract.chain,
}),
)
: undefined

if (receipt?.status) {
if (showOnceAirdropModal) {
setShowOnceAirdropModal((prevState) => !prevState)
}
queryClient.invalidateQueries({
queryKey: [account, '/airdrop-claimed'],
})
toastSuccess(t('Success!'), <ToastDescriptionWithTx txHash={receipt.transactionHash} />)
}
} catch (error: any) {
const errorDescription = `${error.message} - ${error.data?.message}`
Expand All @@ -147,7 +151,21 @@ const V3AirdropModal: React.FC = () => {
setShow(false)
setIsLoading(false)
}
}
}, [
account,
v3ForSC,
v3MerkleProofs,
v3AirdropContract,
queryClient,
showOnceAirdropModal,
setShowOnceAirdropModal,
setShow,
setIsLoading,
toastSuccess,
toastError,
fetchWithCatchTxError,
t,
])

const hasPart1 = useMemo(() => (data ? Object.values(data.part1).find((i) => i !== null) : false), [data])
const hasPart2 = useMemo(() => (data ? Object.values(data.part2).find((i) => i !== null) : false), [data])
Expand Down
7 changes: 4 additions & 3 deletions apps/web/src/components/Menu/UserMenu/WalletInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import useTokenBalance, { useBSCCakeBalance } from 'hooks/useTokenBalance'
import { formatBigInt, getFullDisplayBalance } from '@pancakeswap/utils/formatBalance'
import InternalLink from 'components/Links'
import { useDomainNameForAddress } from 'hooks/useDomain'
import { useState } from 'react'
import { useCallback, useState } from 'react'
import { isMobile } from 'react-device-detect'
import { getBlockExploreLink, getBlockExploreName } from 'utils'
import { Address } from 'viem'
Expand Down Expand Up @@ -60,10 +60,11 @@ const WalletInfo: React.FC<WalletInfoProps> = ({ hasLowNativeBalance, onDismiss
const [mobileTooltipShow, setMobileTooltipShow] = useState(false)
const { logout } = useAuth()

const handleLogout = () => {
const handleLogout = useCallback(() => {
onDismiss?.()
logout()
}
}, [onDismiss, logout])

const {
tooltip: buyCryptoTooltip,
tooltipVisible: buyCryptoTooltipVisible,
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/components/Menu/UserMenu/WalletTransactions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useAllSortedRecentTransactions } from 'state/transactions/hooks'
import { useTranslation } from '@pancakeswap/localization'
import { clearAllTransactions } from 'state/transactions/actions'
import isEmpty from 'lodash/isEmpty'
import { useCallback } from 'react'
import TransactionRow from './TransactionRow'
import { chains } from '../../../utils/wagmi'

Expand All @@ -24,9 +25,9 @@ const WalletTransactions: React.FC<React.PropsWithChildren<WalletTransactionsPro

const hasTransactions = !isEmpty(sortedTransactions)

const handleClearAll = () => {
const handleClearAll = useCallback(() => {
dispatch(clearAllTransactions())
}
}, [dispatch])

return (
<Box minHeight="120px">
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/components/PhishingWarningBanner/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CloseIcon, Flex, IconButton, Text, useMatchBreakpoints } from '@pancakeswap/uikit'
import { usePhishingBanner } from '@pancakeswap/utils/user'
import { CSSProperties, useEffect, useMemo, useRef, useState } from 'react'
import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { styled } from 'styled-components'
import 'swiper/css'
import 'swiper/css/effect-fade'
Expand Down Expand Up @@ -184,14 +184,14 @@ const PhishingWarningBanner: React.FC<React.PropsWithChildren> = () => {
}
}, [remainingTimer, showAnimation, step, nextItem])

const handleClickNext = () => {
const handleClickNext = useCallback(() => {
setTimeout(() => {
setStep(nextItem)
setPerCentage(0)
setRemainingTimer(DISPLAY_TIMER)
setShowAnimation(true)
}, 600)
}
}, [nextItem, setStep, setPerCentage, setRemainingTimer, setShowAnimation])

return (
<Container className="warning-banner" $background={banner.background}>
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/components/TransactionDetailModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ import { ModalV2 } from '@pancakeswap/uikit'
import { useAppDispatch } from 'state'
import { toggleFarmTransactionModal } from 'state/global/actions'
import { useFarmHarvestTransaction } from 'state/global/hooks'
import { useCallback } from 'react'
import FarmTransactionModal from './FarmTransactionModal'

const TransactionsDetailModal = () => {
const { showModal } = useFarmHarvestTransaction()
const dispatch = useAppDispatch()

const closeModal = () => {
const closeModal = useCallback(() => {
dispatch(toggleFarmTransactionModal({ showModal: false }))
}
}, [dispatch])

return (
<ModalV2 isOpen={showModal} closeOnOverlayClick onDismiss={closeModal}>
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/hooks/useCakeApprove.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ToastDescriptionWithTx } from 'components/Toast'
import { useCallWithGasPrice } from 'hooks/useCallWithGasPrice'
import useCatchTxError from 'hooks/useCatchTxError'
import { useCake } from 'hooks/useContract'
import { useCallback } from 'react'

const useCakeApprove = (setLastUpdated: () => void, spender, successMsg) => {
const { t } = useTranslation()
Expand All @@ -13,7 +14,7 @@ const useCakeApprove = (setLastUpdated: () => void, spender, successMsg) => {
const { callWithGasPrice } = useCallWithGasPrice()
const cakeContract = useCake()

const handleApprove = async () => {
const handleApprove = useCallback(async () => {
const receipt = await fetchWithCatchTxError(() => {
return callWithGasPrice(cakeContract, 'approve', [spender, MaxUint256])
})
Expand All @@ -24,7 +25,7 @@ const useCakeApprove = (setLastUpdated: () => void, spender, successMsg) => {
)
setLastUpdated()
}
}
}, [cakeContract, spender, fetchWithCatchTxError, callWithGasPrice, t, toastSuccess, successMsg, setLastUpdated])

return { handleApprove, pendingTx }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useMemo } from 'react'
import { useState, useMemo, useCallback } from 'react'
import { SiweMessage } from 'siwe'
import { useAccount } from 'wagmi'
import { useSignMessage } from '@pancakeswap/wagmi'
Expand All @@ -17,7 +17,7 @@ const LoginButton = () => {

const isReady = useMemo(() => address && chainId && !isLoading, [isLoading, address, chainId])

const handleLogin = async () => {
const handleLogin = useCallback(async () => {
try {
setIsLoading(true)
const nonceResponse = await fetch('/api/affiliates-program/affiliate-nonce')
Expand Down Expand Up @@ -52,7 +52,7 @@ const LoginButton = () => {
} finally {
setIsLoading(false)
}
}
}, [address, chainId, queryClient, setIsLoading, signMessageAsync])

return (
<Button display="block" m="40px auto" width={180} disabled={!isReady} onClick={handleLogin}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react'
import { useCallback, useMemo, useState } from 'react'
import { Flex, Text, Input, Box, Button, ArrowForwardIcon, useMatchBreakpoints, useToast } from '@pancakeswap/uikit'
import { styled } from 'styled-components'
import { BIG_ONE_HUNDRED } from '@pancakeswap/utils/bigNumber'
Expand Down Expand Up @@ -106,7 +106,7 @@ const MyReferralLink: React.FC<React.PropsWithChildren<MyReferralLinkProps>> = (

const linkId = useMemo(() => note || defaultLinkId, [note, defaultLinkId])

const handleGenerateLink = async () => {
const handleGenerateLink = useCallback(async () => {
try {
setIsLoading(true)

Expand Down Expand Up @@ -147,15 +147,30 @@ const MyReferralLink: React.FC<React.PropsWithChildren<MyReferralLinkProps>> = (
} finally {
setIsLoading(false)
}
}

const handleInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const textValue = e.target.value
const reg = /^[a-zA-Z0-9]+$/
if (reg.test(textValue) || textValue === '') {
setNote(textValue)
}
}
}, [
address,
linkId,
percentage,
refreshAffiliateInfo,
refresh,
setNote,
setIsLoading,
signMessageAsync,
t,
toastSuccess,
toastError,
])

const handleInput = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const textValue = e.target.value
const reg = /^[a-zA-Z0-9]+$/
if (reg.test(textValue) || textValue === '') {
setNote(textValue)
}
},
[setNote],
)

return (
<Box>
Expand Down
Loading

0 comments on commit 2822d2a

Please sign in to comment.