Skip to content

Commit d933676

Browse files
committed
Fix performance issue on scorecard editor page
1 parent 27418e1 commit d933676

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/apps/review/src/pages/scorecards/EditScorecardPage/components/CalculatedWeightsSum.tsx

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { FC } from 'react'
2-
import { useFormContext } from 'react-hook-form'
1+
import { FC, useMemo } from 'react'
2+
import { useFormContext, useWatch } from 'react-hook-form'
33
import classNames from 'classnames'
44

55
import styles from './CalculatedWeightsSum.module.scss'
@@ -13,11 +13,25 @@ interface CalculatedWeightsSumProps {
1313

1414
const CalculatedWeightsSum: FC<CalculatedWeightsSumProps> = props => {
1515
const form = useFormContext()
16-
const fields = form.watch(props.fieldName)
16+
const watchedFields = useWatch({
17+
control: form.control,
18+
defaultValue: [],
19+
name: props.fieldName,
20+
}) as { weight?: number | string | null }[] | undefined
1721

18-
const weightsSum = fields.reduce(
19-
(sum: number, field: { weight: string | number | undefined }) => (Number(field.weight) || 0) + sum,
20-
0,
22+
const fields = useMemo(
23+
() => (Array.isArray(watchedFields) ? watchedFields : []),
24+
[watchedFields],
25+
)
26+
27+
const weightsSum = useMemo(
28+
() => fields.reduce(
29+
(sum: number, field: { weight?: string | number | null }) => (
30+
Number(field?.weight ?? 0) + sum
31+
),
32+
0,
33+
),
34+
[fields],
2135
)
2236

2337
return (

0 commit comments

Comments
 (0)