From 2448b7f8832853486955ffa9a019a537ddc81559 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Sat, 29 Aug 2020 13:16:27 +0200 Subject: [PATCH] Hooks with useMemo (no extra re-renders) (#3567) * Hooks with useMemo (no extra re-renders) * Extract defaults * sorted targets * Linting --- .../src/electron/contentSecurityPolicy.ts | 2 +- packages/page-staking/src/useSortedTargets.ts | 27 +++++---------- packages/react-hooks/src/useIncrement.ts | 1 + packages/react-hooks/src/useOwnStashInfos.ts | 16 ++++----- packages/react-hooks/src/useOwnStashes.ts | 33 ++++++++----------- packages/react-hooks/src/useRegistrars.ts | 20 +++++------ packages/react-hooks/src/useStashIds.ts | 3 +- packages/react-hooks/src/useVotingStatus.ts | 18 +++++----- 8 files changed, 50 insertions(+), 70 deletions(-) diff --git a/packages/apps-electron/src/electron/contentSecurityPolicy.ts b/packages/apps-electron/src/electron/contentSecurityPolicy.ts index f4538c03cc..dfa37aae50 100644 --- a/packages/apps-electron/src/electron/contentSecurityPolicy.ts +++ b/packages/apps-electron/src/electron/contentSecurityPolicy.ts @@ -4,7 +4,7 @@ import { HeadersReceivedResponse, session } from 'electron'; -export const setupContentSecurityPolicy = (environment: string): void => { +export const setupContentSecurityPolicy = (_: string): void => { session.defaultSession.webRequest.onHeadersReceived((details, cb: (headersReceivedResponse: HeadersReceivedResponse) => void) => { const headersReceivedResponse = { responseHeaders: { diff --git a/packages/page-staking/src/useSortedTargets.ts b/packages/page-staking/src/useSortedTargets.ts index 048788a103..70fde2ea41 100644 --- a/packages/page-staking/src/useSortedTargets.ts +++ b/packages/page-staking/src/useSortedTargets.ts @@ -7,13 +7,14 @@ import { Balance, ValidatorPrefs, ValidatorPrefsTo196 } from '@polkadot/types/in import { SortedTargets, TargetSortBy, ValidatorInfo } from './types'; import BN from 'bn.js'; -import { useEffect, useState } from 'react'; +import { useMemo, useState } from 'react'; import { registry } from '@polkadot/react-api'; import { useAccounts, useApi, useCall, useDebounce } from '@polkadot/react-hooks'; import { Option } from '@polkadot/types'; import { BN_ONE, BN_ZERO, formatBalance } from '@polkadot/util'; const PERBILL = new BN(1_000_000_000); +const EMPTY_PARTIAL = {}; function baseBalance (): BN { return new BN('1'.padEnd(formatBalance.getDefaults().decimals + 4, '0')); @@ -166,23 +167,13 @@ export default function useSortedTargets (favorites: string[]): SortedTargets { const lastReward = useCall(lastEra && api.query.staking.erasValidatorReward, [lastEra], transformReward); const [calcWith, setCalcWith] = useState(baseBalance()); const calcWithDebounce = useDebounce(calcWith); - const [state, setState] = useState({ setCalcWith }); - useEffect((): void => { - electedInfo && waitingInfo && setState(({ calcWith, setCalcWith }) => ({ - ...extractInfo(allAccounts, calcWithDebounce, electedInfo, waitingInfo, favorites, lastReward), - calcWith, - lastReward, - setCalcWith - })); - }, [allAccounts, calcWithDebounce, electedInfo, favorites, lastReward, waitingInfo]); + const partial = useMemo( + () => electedInfo && waitingInfo + ? extractInfo(allAccounts, calcWithDebounce, electedInfo, waitingInfo, favorites, lastReward) + : EMPTY_PARTIAL, + [allAccounts, calcWithDebounce, electedInfo, favorites, lastReward, waitingInfo] + ); - useEffect((): void => { - calcWith && setState((state) => ({ - ...state, - calcWith - })); - }, [calcWith]); - - return state; + return { ...partial, calcWith, lastReward, setCalcWith }; } diff --git a/packages/react-hooks/src/useIncrement.ts b/packages/react-hooks/src/useIncrement.ts index 942732a3df..ec35220bc7 100644 --- a/packages/react-hooks/src/useIncrement.ts +++ b/packages/react-hooks/src/useIncrement.ts @@ -8,6 +8,7 @@ import useIsMountedRef from './useIsMountedRef'; export default function useIncrement (defaultValue = 1): [number, () => void, (value: number) => void] { const mountedRef = useIsMountedRef(); const [value, setValue] = useState(defaultValue); + const increment = useCallback( (): void => { mountedRef.current && setValue((value: number) => ++value); diff --git a/packages/react-hooks/src/useOwnStashInfos.ts b/packages/react-hooks/src/useOwnStashInfos.ts index 159a2265c2..4de89cf0cc 100644 --- a/packages/react-hooks/src/useOwnStashInfos.ts +++ b/packages/react-hooks/src/useOwnStashInfos.ts @@ -7,7 +7,7 @@ import { AccountId, ValidatorPrefs } from '@polkadot/types/interfaces'; import { Codec, ITuple } from '@polkadot/types/types'; import { StakerState } from './types'; -import { useEffect, useState } from 'react'; +import { useEffect, useMemo, useState } from 'react'; import { u8aConcat, u8aToHex } from '@polkadot/util'; import useAccounts from './useAccounts'; @@ -64,7 +64,6 @@ export default function useOwnStashInfos (): StakerState[] | undefined { const ownStashes = useOwnStashes(); const allStashes = useStashIds(); const [queried, setQueried] = useState(); - const [state, setState] = useState(); useEffect((): () => void => { let unsub: (() => void) | undefined; @@ -97,13 +96,12 @@ export default function useOwnStashInfos (): StakerState[] | undefined { }; }, [api, mountedRef, ownStashes]); - useEffect((): void => { - allAccounts && allStashes && ownStashes && queried && ownStashes.length === Object.keys(queried).length && setState( - ownStashes + return useMemo( + () => allStashes && ownStashes && queried && ownStashes.length === Object.keys(queried).length + ? ownStashes .filter(([stashId]) => queried[stashId]) .map(([stashId]) => getStakerState(stashId, allAccounts, allStashes, queried[stashId])) - ); - }, [allAccounts, allStashes, ownStashes, queried]); - - return state; + : undefined, + [allAccounts, allStashes, ownStashes, queried] + ); } diff --git a/packages/react-hooks/src/useOwnStashes.ts b/packages/react-hooks/src/useOwnStashes.ts index 312ca1a9cf..4cda45085b 100644 --- a/packages/react-hooks/src/useOwnStashes.ts +++ b/packages/react-hooks/src/useOwnStashes.ts @@ -4,13 +4,12 @@ import { AccountId, StakingLedger } from '@polkadot/types/interfaces'; -import { useEffect, useState } from 'react'; +import { useMemo } from 'react'; import { Option } from '@polkadot/types'; import useAccounts from './useAccounts'; import useApi from './useApi'; import useCall from './useCall'; -import useIsMountedRef from './useIsMountedRef'; type IsInKeyring = boolean; @@ -34,31 +33,25 @@ function getStashes (allAccounts: string[], ownBonded: Option[], ownL export default function useOwnStashes (): [string, IsInKeyring][] | undefined { const { allAccounts, hasAccounts } = useAccounts(); - const mountedRef = useIsMountedRef(); const { api } = useApi(); const ownBonded = useCall[]>(hasAccounts && api.query.staking?.bonded.multi, [allAccounts]); const ownLedger = useCall[]>(hasAccounts && api.query.staking?.ledger.multi, [allAccounts]); - const [state, setState] = useState<[string, IsInKeyring][] | undefined>(); - useEffect((): void => { - mountedRef.current && ownBonded && ownLedger && setState( - getStashes(allAccounts, ownBonded, ownLedger) - ); - }, [allAccounts, mountedRef, ownBonded, ownLedger]); - - return state; + return useMemo( + () => ownBonded && ownLedger + ? getStashes(allAccounts, ownBonded, ownLedger) + : undefined, + [allAccounts, ownBonded, ownLedger] + ); } export function useOwnStashIds (): string[] | undefined { - const mountedRef = useIsMountedRef(); const ownStashes = useOwnStashes(); - const [stashIds, setStashIds] = useState(); - useEffect((): void => { - mountedRef.current && ownStashes && setStashIds( - ownStashes.map(([stashId]) => stashId) - ); - }, [mountedRef, ownStashes]); - - return stashIds; + return useMemo( + () => ownStashes + ? ownStashes.map(([stashId]) => stashId) + : undefined, + [ownStashes] + ); } diff --git a/packages/react-hooks/src/useRegistrars.ts b/packages/react-hooks/src/useRegistrars.ts index 9277813d72..5dbd426f82 100644 --- a/packages/react-hooks/src/useRegistrars.ts +++ b/packages/react-hooks/src/useRegistrars.ts @@ -4,7 +4,7 @@ import { RegistrarInfo } from '@polkadot/types/interfaces'; -import { useEffect, useState } from 'react'; +import { useMemo } from 'react'; import { Option } from '@polkadot/types'; import useAccounts from './useAccounts'; @@ -31,12 +31,11 @@ export default function useRegistrars (skipQuery?: boolean): State { const { api } = useApi(); const { allAccounts, hasAccounts } = useAccounts(); const query = useCall[]>(!skipQuery && hasAccounts && api.query.identity?.registrars); - const [state, setState] = useState({ isRegistrar: false, registrars: [] }); // determine if we have a registrar or not - registrars are allowed to approve - useEffect((): void => { - if (allAccounts && query) { - const registrars = query + return useMemo( + (): State => { + const registrars = (query || []) .map((registrar, index): RegistrarNull => ({ address: registrar.isSome ? registrar.unwrap().account.toString() @@ -45,12 +44,11 @@ export default function useRegistrars (skipQuery?: boolean): State { })) .filter((registrar): registrar is Registrar => !!registrar.address); - setState({ + return { isRegistrar: registrars.some(({ address }) => allAccounts.includes(address)), registrars - }); - } - }, [allAccounts, query]); - - return state; + }; + }, + [allAccounts, query] + ); } diff --git a/packages/react-hooks/src/useStashIds.ts b/packages/react-hooks/src/useStashIds.ts index 1934793972..26652753af 100644 --- a/packages/react-hooks/src/useStashIds.ts +++ b/packages/react-hooks/src/useStashIds.ts @@ -13,7 +13,6 @@ const transformStashes = { export default function useStashIds (): string[] | undefined { const { api } = useApi(); - const allStashes = useCall(api.derive.staking.stashes, undefined, transformStashes); - return allStashes; + return useCall(api.derive.staking.stashes, undefined, transformStashes); } diff --git a/packages/react-hooks/src/useVotingStatus.ts b/packages/react-hooks/src/useVotingStatus.ts index 4b497d2ea0..e86da8e2af 100644 --- a/packages/react-hooks/src/useVotingStatus.ts +++ b/packages/react-hooks/src/useVotingStatus.ts @@ -5,7 +5,7 @@ import { BlockNumber, Votes } from '@polkadot/types/interfaces'; import BN from 'bn.js'; -import { useEffect, useState } from 'react'; +import { useMemo } from 'react'; import { ApiPromise } from '@polkadot/api'; import useApi from './useApi'; @@ -19,6 +19,8 @@ interface State { remainingBlocks: BN | null; } +const DEFAULT_STATUS = { hasFailed: false, hasPassed: false, isCloseable: false, isVoteable: false, remainingBlocks: null }; + function getStatus (api: ApiPromise, bestNumber: BlockNumber, votes: Votes, numMembers: number, section: 'council' | 'technicalCommittee'): State { if (!votes.end) { return { @@ -50,13 +52,11 @@ function getStatus (api: ApiPromise, bestNumber: BlockNumber, votes: Votes, numM export default function useVotingStatus (votes: Votes | null | undefined, numMembers: number, section: 'council' | 'technicalCommittee'): State { const { api } = useApi(); const bestNumber = useCall(api.derive.chain.bestNumber); - const [state, setState] = useState({ hasFailed: false, hasPassed: false, isCloseable: false, isVoteable: false, remainingBlocks: null }); - useEffect((): void => { - bestNumber && votes && setState( - getStatus(api, bestNumber, votes, numMembers, section) - ); - }, [api, bestNumber, numMembers, section, votes]); - - return state; + return useMemo( + () => bestNumber && votes + ? getStatus(api, bestNumber, votes, numMembers, section) + : DEFAULT_STATUS, + [api, bestNumber, numMembers, section, votes] + ); }