Home > Enterprise >  Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Time:11-30

What i want is when i click on button the React component should re-render

And i also Don't want to re-Render the complete webiste on this particular component has to re-render

It tried using hooks to re-render the page but it gives me error as shown above and also tried using forceUpdate() Hook but that still gives me the same error

re-Render the component

This is the javascript of same file

const LeftCard = ({ cardData: cardComponent, getFileName }) => {
  let emptyArr=[];
  let pageNo=10;
  const [loadComponentByPage,setPageArr]=useState(undefined);
       
if(pageNo){setPageArr(emptyArr);console.log(emptyArr)}
  
pageNo<10?pageNo=10:''
pageNo===10 ? pageChange(0):null

function pageChange(num){      <-------- This function is getting called on button click

if(cardComponent !==undefined) {
  const mainArray=cardComponent.sort((a,b)=>b.id-a.id).map(val=>{return val});
  const arrayLength=cardComponent.length;
    if(pageNo===10 && num===-10)return;
        if(arrayLength<pageNo && num ===10)return;
            pageNo =num
              emptyArr=[]
                for(let i=pageNo-10;i<=pageNo;i  ){
                    if(mainArray[i]!==undefined){
                        emptyArr.push( mainArray[i])                        
        }
      }
      
    }
}


if(loadComponentByPage ===undefined )return

This is jsx of same file

  return (
    <div>
      {loadComponentByPage.sort((a, b) => (a.id - b.id))
          .map((element, i) => {
            return (
              <div key={i}>
                <span className="image-overflow flex ">
                  <img className="left-sec-image ml2 link Dim" src={element.image} alt={element.topicname}></img>
                    <div>
                        <h4 className=" ml4 mr2 light-purple">{element.topicname}</h4>
                    </div>
                </span>
              </div>
          );
        }).reverse()}
       
        <div>
        <div className='ml5'>
    These are the button that calling the function------->        <button className='ml7' onClick={()=>{pageChange(-10);doNothing()}}><ArrowBackIosSharpIcon /></button>

   These are the button that calling the function------->  <button className='ml6'  onClick={()=>{pageChange(10);doNothing()}}><ArrowForwardIosSharpIcon /></button>
        </div>
    </div>
  
    </div>
  )};
export default LeftCard;

CodePudding user response:

The problem you are having is that you've created an infinite loop of renders.
It's a common pitfall in React and is something to look out for.

In React, a component re-renders whenever one of these 2 cases occurs:

  1. Whenever there is a change in the component's local state.
  2. Whenever any of it's parent components themselves are re-rendered.

So what happens is the following:

  1. When the component renders, the value of pageNo is 10, which is "truthy".
  2. This means that we enter the if block and setPageArr is called, thus setting the component's state.
  3. The component is re-rendered due to the state update.
  4. The value of pageNo is still 10, so we enter the if block and set the state again.

And this cycle repeats, creating an infinite loop.

Typically, when faced with an infinite loop, the browser would freeze and ultimately crash.
The error you are getting is due to React "catching" the problem and preventing the freeze.

To fix it we have 2 options:

  1. Since in this case we already know the initial value of the state is an empty array, we can simply initialize it as such.

Example:

const [loadComponentByPage,setPageArr]=useState([]);
  1. If we don't know the initial value, such as the case with values fetched from an external API / etc.. We can utilize the useEffect hook.

Example:

useEffect(() => {
   setPageArr(emptyArr)
}, []) // A `useEffect` hook with an empty dependency array should run only once when the component mounts.

Either way, this bit needs to go -> if(pageNo){setPageArr(emptyArr);console.log(emptyArr)}

  • Related