Update state handling in CaptchaProvider

Adjusted the way the 'instance' state is handled in CaptchaProvider by utilizing useRef and useCallback from React. Now, instead of managing 'instance' with useState, it is stored in a reference through useRef to prevent unnecessary re-renders. The 'setInstance' function has been updated to set this reference, ensuring the 'instance' is kept up-to-date.
This commit is contained in:
giancarlo
2024-04-27 20:24:40 +07:00
parent 0ee501fe9d
commit a2211c7e75

View File

@@ -1,6 +1,6 @@
'use client';
import { createContext, useState } from 'react';
import { createContext, useCallback, useRef, useState } from 'react';
import { TurnstileInstance } from '@marsidev/react-turnstile';
@@ -23,10 +23,16 @@ export const Captcha = createContext<{
export function CaptchaProvider(props: { children: React.ReactNode }) {
const [token, setToken] = useState<string>('');
const [instance, setInstance] = useState<TurnstileInstance | null>(null);
const instanceRef = useRef<TurnstileInstance | null>(null);
const setInstance = useCallback((ref: TurnstileInstance) => {
instanceRef.current = ref;
}, []);
return (
<Captcha.Provider value={{ token, setToken, instance, setInstance }}>
<Captcha.Provider
value={{ token, setToken, instance: instanceRef.current, setInstance }}
>
{props.children}
</Captcha.Provider>
);