Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook "useEffect" cannot be called inside a callback error occurs

Tags:

reactjs

The error below sometimes occurs I don't know why. Every code seems to work but only an error occurs.

React Hook "useEffect" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks Search for the keywords to learn more about each error.

import { useEffect, useState } from 'react'

import { useAuthContext } from 'src/contexts/Auth'

import { brandRepository } from 'src/repositories/BrandRepository'

export default function TestBrand() {
  const [brands, setBrands] = useState<any[]>()

  const { currentUser } = useAuthContext()

  useEffect(() => {
    if(!currentUser) return
    useEffect(() => {
      brandRepository.list(currentUser.id).then(async (docs: any[]) => {
        if(!docs) return
        await setBrands(docs)
      })
    }, [])
    }, [currentUser])

  if(!currentUser) {
    return <div>Loading...</div>
  }

  return (
    <div>test</div>
  )
}
like image 298
k10a Avatar asked Oct 18 '25 06:10

k10a


2 Answers

You cannot use useEffect inside another useEffect. Try using both the hooks separately as it forbids the rules of hooks. Better don't use the second useEffect as I do not see any specific use of it. Refer this https://reactjs.org/docs/hooks-rules.html

like image 185
Maddy Avatar answered Oct 21 '25 13:10

Maddy


You cant call useEffect or other hooks inside a function or CB you can only call hooks inside Function component https://reactjs.org/docs/hooks-rules.html

Blockquote Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls

like image 45
Amirhossien Salighedar Avatar answered Oct 21 '25 11:10

Amirhossien Salighedar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!