'Too many renderers when using useState for spinner

there. I need to make loading spinner with hook, while my component counts some data. And when it's done it spinner should stop. But when i set useHook to true, i recieve infinite re-renderers.

const myCard = () => {
  [loading, setLoading] = useState()
  if (condition) {
    setLoading(true)
   
   //Some countiong


   // When it's over set loading
   setLoading(false)
  }

  return (
    <Card loading={loading}>
       ...Some card content
    </Card>
  )
}

Could anyone tell me what am i doing wrang here ?



Solution 1:[1]

Put your loading logic inside the useEffect Hook

 const myCard = () => {
    [loading, setLoading] = useState(false) //always specify an initial value

    useEffect(() => {
       if (condition) {
        setLoading(true)
       
       //Some countiong
    
    
       // When it's over set loading
       setLoading(false)
      }
  },[condition]) //will render when condition change
      
    
      return (
        <Card loading={loading}>
           ...Some card content
        </Card>
      )
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Khant