Sava
Sava

Reputation: 133

Too many re-renders. React limits the number of renders to prevent an infinite loop. UI and conole error

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

Upvotes: 0

Views: 346

Answers (2)

Ayyan Amir
Ayyan Amir

Reputation: 1

App.js

import React ,{useState} from 'react';
import { Child } from './Components/Child';


function App() {
    let value = [1,2,4,6];
    const number = (number,val)=>{
    console.log(`${number}: value ${val}`)
}
return (
<div className="App">
  {
    value.map((item , i)=>{
      return <Child count = {item} itemName={i} key={i} muFunc={number}/>
    })
  }
</div>
);
}

export default App;

Child.js

import React,{useState,useEffect} from 'react';

export function Child ({count,itemName,muFunc}) {
    const [number, setnumber] = useState(count);
    useEffect(() => {
        muFunc(itemName,number);
    }, [number]);
    const makeCount = {
        add: () => setnumber(number + 1),
        discount: () => setnumber(number - 1)
   }

    // Send this number to parent ??
    return(
        <>
            <h3>{itemName}</h3>
            <button onClick ={makeCount.discount}>decrement</button>
            <input value={number} onChange={(e)=>setnumber(e.target.value)} />
            <button onClick ={makeCount.add}>Increment</button>
            <br/>
        
        </>
    )  
}

Upvotes: 0

Domino987
Domino987

Reputation: 8804

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.

Upvotes: 1

Related Questions