useCallback is recreate function when variable is not in dependency list

30 views Asked by At

Hello I have a Login modal where I also have function onSubmit, it's next js application. So it's changing state of setIsLoading, then it's recreating component, but not the function? Am I right?. There is another quastion below.

    const onSubmit : SubmitHandler<FieldValues> = (data)=>{
        setIsLoading(true);
        signIn('credentials',{
            ...data,
            redirect: false
        }).then((callback)=>{
            setIsLoading(false)

            if(callback?.ok){
                toast.success('Logged in')
                router.refresh()
                loginModal.onClose()
            }
            if(callback?.error){
                toast.error(callback.error)
            }
        })
    }
  return (
    <div>
        <Modal disabled={isLoading}
         isOpen={loginModal.isOpen} 
         body={bodyContent} title='Login'
          actionLabel='Continue' 
          onClose={loginModal.onClose} 
          onSubmit={handleSubmit(onSubmit)}
          footer={footerContent}
          ></Modal>
    </div>
  )}

Then I have Modal with function that handles submit, and when I click multiple times on button, it's not sending multiple request, after first submit it's set disabled to true, but it's shouldn't because useCallback must use old values so it must be disabled == false. Help me, I can't figure out why it's happening. Also, why we use functions on useCallback, how it's suppose to change?

const handleSubmit = useCallback(()=>{
console.log(disabled)
if(disabled)
return
onSubmit()
}, [onSubmit])

I tried to google the question

1

There are 1 answers

0
Adam Jenkins On BEST ANSWER

useCallback and useMemo are drastically overused and then you run into problems like this where you're not sure if you should leave things out of the dependency list and then you get stuck and confused about the whole thing.

The simplest solution is to just not use useCallback/useMemo (unless and until you are absolutely sure you need them, and you'll know when that is, trust me)

const handleSubmit = () => {
 if(!disabled) {
   return onSubmit()
 }
}