Home > Mobile >  How to fix the following "Too many re-renders error" in React?
How to fix the following "Too many re-renders error" in React?

Time:11-27

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).

import { useState } from "react";
import * as ReactDOM from "react-dom";

let keys = ["a", "b"];

function App() {
  let [keysState, setKeysState] = useState([]);

  setKeysState((keysState = keys));

  return (
    <div>
      {keysState.map((key) => (
        <li>{key}</li>
      ))}{" "}
    </div>
  );
}

const rootElement = document.getElementById("root");

ReactDOM.createRoot(rootElement).render(<App />);

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: enter image description here

Second, if you want to provide an initial value to your keyState, you should do it using the setState hook, just like this:

const [keyState, setKeyState] = useState(["a","b"]);

This would create the keyState variable and initialize it with ["a","b"], as well as provide the setKeyState function.

I believe this is the main problem with this code. This redundance is causing the perpetual re-render.

Finally, you should have some way to react to state changes. This will be given by the useEffect hook.

useEffect(() => {
    // Things to perform when `stateKeys` changes
},[stateKeys])

The second parameter this hook receives [stateKeys] is exactly to prevent a perpetual re-rendering. It tells the hook it should run only when the variables inside this array changes.

It seems to me, allow please don't be offended for me to say, that you missed something in React way of doing things. Specially when it comes to React Hooks. I suggest you to read the documentation again:

https://reactjs.org/docs/hooks-state.html

  • Related