Skip to content

Commit

Permalink
refactor(clerk-js): Avoid useEffect usage for feedbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
desiprisg committed Oct 3, 2023
1 parent eb19804 commit a053296
Showing 1 changed file with 31 additions and 25 deletions.
56 changes: 31 additions & 25 deletions packages/clerk-js/src/ui/elements/FormControl.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { FieldId } from '@clerk/types';
import type { ClerkAPIError } from '@clerk/types';
import type { PropsWithChildren } from 'react';
import { useRef } from 'react';
import { useEffect } from 'react';
import React, { forwardRef, useCallback, useMemo, useState } from 'react';

Expand Down Expand Up @@ -148,15 +149,15 @@ type FormFeedbackProps = Partial<ReturnType<typeof useFormControlFeedback>['debo

export const FormFeedback = (props: FormFeedbackProps) => {
const { id, elementDescriptors, feedback, feedbackType = 'info' } = props;
const [feedbacks, setFeedbacks] = useState<{
const feedbacksRef = useRef<{
a?: Feedback;
b?: Feedback;
}>({ a: { feedback, feedbackType, shouldEnter: true }, b: undefined });
const { calculateHeight: calculateHeightA, height: heightA } = useCalculateErrorTextHeight({
feedback: feedbacks.a?.feedback || '',
feedback: feedbacksRef.current.a?.feedback || '',
});
const { calculateHeight: calculateHeightB, height: heightB } = useCalculateErrorTextHeight({
feedback: feedbacks.b?.feedback || '',
feedback: feedbacksRef.current.b?.feedback || '',
});
const [heightMax, setHeightMax] = useState(Math.max(heightA, heightB));

Expand All @@ -168,28 +169,33 @@ export const FormFeedback = (props: FormFeedbackProps) => {
success: descriptors.formFieldSuccessText,
};

useEffect(() => {
setFeedbacks(oldFeedbacks => {
if (oldFeedbacks.a?.shouldEnter) {
return {
a: { ...oldFeedbacks.a, shouldEnter: false },
b: {
feedback,
feedbackType,
shouldEnter: true,
},
};
} else {
return {
a: {
feedback,
feedbackType,
shouldEnter: true,
},
b: { ...oldFeedbacks.b, shouldEnter: false },
};
}
});
const feedbacks = useMemo(() => {
const oldFeedbacks = feedbacksRef.current;
let result: {
a?: Feedback;
b?: Feedback;
};
if (oldFeedbacks.a?.shouldEnter) {
result = {
a: { ...oldFeedbacks.a, shouldEnter: false },
b: {
feedback,
feedbackType,
shouldEnter: true,
},
};
} else {
result = {
a: {
feedback,
feedbackType,
shouldEnter: true,
},
b: { ...oldFeedbacks.b, shouldEnter: false },
};
}
feedbacksRef.current = result;
return result;
}, [feedback, feedbackType]);

useEffect(() => {
Expand Down

0 comments on commit a053296

Please sign in to comment.