0
votes

import { useState, useEffect } from 'react' import './App.css';

function App() {

const [count, setCount] = useState(0)

useEffect(() => {

console.log('render')

}, [count])

First: show me on UI but send me error on conosle: Too many re-renders. React limits the number of renders to prevent an infinite loop.

const plusCount = () => {

setCount(count + 1)   }  

const minsCount = () => {

setCount(count - 1)   }

Second : do not sho em on UI send me error on UI: Too many re-renders. React limits the number of renders to prevent an infinite loop.

const makeCount = {

add:setCount(count + 1),

discount:  setCount(count - 1)

}

return (

  <h1>Exercise</h1>
  <p>Cunt: <b>{count}</b></p>
  <button onClick={plusCount}>Add</button>
  <button onClick={minsCount}>Discount</button>

</div>

) }

export default App;

Guestion: Why is this message show me error on both time, but on first let me show on UI on the second do not show me on UI

1

1 Answers

1
votes

You are executing the setCount function on render, which causes a rerender which results in an infinity loop:

const makeCount = {
     add: setCount(count + 1),
     discount:setCount(count - 1)
}

This object actually call the setCount function instead of creating an fucntion to be called.

You need to change it to:

const makeCount = {
     add: () => setCount(count + 1),
     discount: () => setCount(count - 1)
}

This will generate new functions called add and discount instead of calling setCount.