Prevent Infinite Re-renders in React

Vikas Tiwari
3 min readOct 3, 2023

Hey awesome people, hope you are great. In this article lets discuss how we can prevent our react application from inifinite re-renders.

Let’s assume you want to render a list of items which have same content and styling. So you decided to utilise map to render all list items in your react project.

You have some scenario where you want to bind click event on each list items respectively.

But when you did so, react throws below error in console.

Infinite Re-renders

What caused this issue?

In React, components re-render when their state or props change. So when you create a new function inside a map function and use it as an event handler, you're creating a new function on each render.

This new function has a different reference compared to the previous render, now even if it performs the same logic. React uses reference equality to determine if a prop or state has changed or not. So when it detects that a prop has a different reference, it triggers a re-render of the component.

As a result, clicking a button triggers a re-render of the entire component, and this process repeats indefinitely, causing an infinite loop.

Let’s look into this and fix this issue

To solve this issue, you can either use the .bind() method to pre-bind the event handler or create a separate functional component for the items to avoid creating new functions on each render.

These approaches ensure that the event handlers maintain the same reference across re-renders and prevent the infinite loop problem.

Use .bind():

You can use the .bind() method to pre-bind the event handler function with its argument:

Using .bind()

Use a Function Component:

Another approach is to create a separate functional component for the items and pass the item as a prop. This way, you don’t need to worry about binding functions:

Function component approach

Conclusion

This is how you can tackle the infinite re-renders issue in your react project. Hope you extracted some knowledge from it.
In case of any doubt or if you just want to say Hi! feel free to reach me on LinkedIn or GitHub.
If you like the blog make sure to take a look at my YouTube channel for more amazing stuff.

--

--