Skip to content

Commit 22e236e

Browse files
quantizorJason Williams
andauthored
perf(FieldArray): add shouldComponentUpdate to cut down on unnecessary renders (#3784)
* revert types * chore: add changeset --------- Co-authored-by: Jason Williams <jwilliams720@bloomberg.net>
1 parent bc9cb28 commit 22e236e

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'formik': patch
3+
---
4+
5+
Improve performance of the `FieldArray` component by adding a `shouldComponentUpdate` check; this should help avoid unnecessary re-renders which may affect the performance of a form.

packages/formik/src/FieldArray.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ export type FieldArrayConfig = {
2727
name: string;
2828
/** Should field array validate the form AFTER array updates/changes? */
2929
validateOnChange?: boolean;
30+
/** Override FieldArray's default shouldComponentUpdate */
31+
shouldUpdate?: (nextProps: {}, props: {}) => boolean;
3032
} & SharedRenderProps<FieldArrayRenderProps>;
3133
export interface ArrayHelpers {
3234
/** Imperatively add a value to the end of an array */
@@ -153,6 +155,26 @@ class FieldArrayInner<Values = {}> extends React.Component<
153155
this.pop = this.pop.bind(this) as any;
154156
}
155157

158+
shouldComponentUpdate(props: any) {
159+
if (this.props.shouldUpdate) {
160+
return this.props.shouldUpdate(props, this.props);
161+
} else if (
162+
props.name !== this.props.name ||
163+
getIn(props.formik.values, this.props.name) !==
164+
getIn(this.props.formik.values, this.props.name) ||
165+
getIn(props.formik.errors, this.props.name) !==
166+
getIn(this.props.formik.errors, this.props.name) ||
167+
getIn(props.formik.touched, this.props.name) !==
168+
getIn(this.props.formik.touched, this.props.name) ||
169+
Object.keys(this.props).length !== Object.keys(props).length ||
170+
props.formik.isSubmitting !== this.props.formik.isSubmitting
171+
) {
172+
return true;
173+
} else {
174+
return false;
175+
}
176+
}
177+
156178
componentDidUpdate(
157179
prevProps: FieldArrayConfig & { formik: FormikContextType<Values> }
158180
) {

0 commit comments

Comments
 (0)