From 2a22b007fb6030152b1bb16adf0b229bdba8cd83 Mon Sep 17 00:00:00 2001 From: Deepak Jose Date: Wed, 11 Dec 2024 22:57:50 +0530 Subject: [PATCH] Creates a similar shouldUpdate funciton fast field internally uses and calls the external shouldUpdate along with it to prevent the component not re-rendering in a few scenarios. --- src/components/Editor/FormikEditor.jsx | 58 ++++++++++++++++++-------- 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/src/components/Editor/FormikEditor.jsx b/src/components/Editor/FormikEditor.jsx index 02287b4a..098ddd54 100644 --- a/src/components/Editor/FormikEditor.jsx +++ b/src/components/Editor/FormikEditor.jsx @@ -16,23 +16,47 @@ const FormikEditor = ( ...otherProps }, ref -) => ( - - {({ field, form, meta }) => ( - form.setFieldTouched(name, true)} - onChange={value => { - form.setFieldValue(name, value); - onChange?.(value); - }} - {...otherProps} - /> - )} - -); +) => { + // Similar to the `shouldComponentUpdate` logic of FastField component. + // https://github.com/jaredpalmer/formik/blob/main/packages/formik/src/FastField.tsx#L75-L93 + // Additionally calls the shouldUpdate function passed from the host application and compares to + // the rest of the values. + const internalShouldUpdate = (prevProps, nextProps) => { + const prevFormikProps = prevProps.formik; + const nextFormikProps = nextProps.formik; + + return ( + prevFormikProps.errors[name] !== nextFormikProps.errors[name] || + prevFormikProps.touched[name] !== nextFormikProps.touched[name] || + Object.keys(nextProps).length !== Object.keys(prevProps).length || + prevFormikProps.isSubmitting !== nextFormikProps.isSubmitting || + Boolean(shouldUpdate?.(prevProps, nextProps)) + ); + }; + + return ( + + {({ field, form, meta }) => ( + { + form.setFieldTouched(name, true); + }} + onChange={value => { + form.setFieldValue(name, value); + onChange?.(value); + }} + {...otherProps} + /> + )} + + ); +}; FormikEditor.displayName = "FormikNeetoEditor";