From 32436d924f3406150c768c44541f109e666085bc Mon Sep 17 00:00:00 2001 From: sachdevavaibhav Date: Wed, 25 Sep 2024 02:18:55 +0530 Subject: [PATCH] fix: infinte re render when parent component re renders onPinReady --- src/components/OtpInput.tsx | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/components/OtpInput.tsx b/src/components/OtpInput.tsx index bee320b..4ea323d 100644 --- a/src/components/OtpInput.tsx +++ b/src/components/OtpInput.tsx @@ -34,23 +34,37 @@ export default function OtpInput({ otpBorderFocusedColor = '#6200EE', textInputProps, }: OtpInputProps) { - const [isInputBoxFocused, setIsInputBoxFocused] = React.useState(autoFocus); - const [otp, setOtp] = React.useState(''); - const [isPinReady, setIsPinReady] = React.useState(false); + const [isInputBoxFocused, setIsInputBoxFocused] = + React.useState(autoFocus); + const [otp, setOtp] = React.useState(''); + const [isPinReady, setIsPinReady] = React.useState(false); const ref = React.useRef(null); + const pinReadyCalledRef = React.useRef(false); + + const handlePinReady = React.useCallback( + (pin: string) => { + if (onPinReady) { + onPinReady(pin); + } + }, + [onPinReady] + ); React.useEffect(() => { - setIsPinReady(otp.length === maxLength); - return () => { + if (otp.length === maxLength) { + setIsPinReady(true); + } else { setIsPinReady(false); - }; + pinReadyCalledRef.current = false; + } }, [maxLength, otp, setIsPinReady]); React.useEffect(() => { - if (isPinReady) { - onPinReady && onPinReady(otp); + if (isPinReady && !pinReadyCalledRef.current) { + handlePinReady(otp); + pinReadyCalledRef.current = true; } - }, [isPinReady, onPinReady, otp]); + }, [isPinReady, onPinReady, otp, handlePinReady]); const boxArray = new Array(maxLength).fill(0); const handleOnPress = () => {