Skip to content
Advertisement

How to fix the following “Too many re-renders error” in React?

I’m trying to render the string array keys into a React component. keys are the keys that the user presses (but I just hard-coded them for the sake of this example).

JavaScript

But I’m getting this error:

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

I know I can avoid this error by creating and onClick handler … but I don’t want to display keysState on click. I want it to display and re-render immediately when keys changes.

Live code: https://codesandbox.io/s/react-18-with-createroot-forked-vgkeiu?file=/src/index.js:0-504

Advertisement

Answer

when the page loads, the setKeysState function gets invoked and it updates the state, updating the state in reactjs causes a re-render and it keeps doing that infinitely. which produces Too many re-renders error.

just pass an initial value to the useState() hook to initialize the state. like this :

JavaScript

NOTE : In your case You do not need The React useState Hook because you’re not tracking the data (keys in your case, you are not be updating it ) just change your component like this :

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement