Skip to content

Commit

Permalink
fix: infinte re render when parent component re renders onPinReady
Browse files Browse the repository at this point in the history
  • Loading branch information
sachdevavaibhav committed Sep 24, 2024
1 parent 2001149 commit 32436d9
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions src/components/OtpInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>(autoFocus);
const [otp, setOtp] = React.useState<string>('');
const [isPinReady, setIsPinReady] = React.useState<boolean>(false);
const ref = React.useRef<RNTextInput>(null);
const pinReadyCalledRef = React.useRef<boolean>(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 = () => {
Expand Down

0 comments on commit 32436d9

Please sign in to comment.