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: https://codesandbox.io/s/react-18-with-createroot-forked-vgkeiu?file=/src/index.js:0-504

useState. You don't need to write thissetKeyStatefunction. It is already returned byuseState, based on de type of the inicial value provided.useState(keys)and not usesetKeysState? I'm not very sure what you mean.setKeyStatefunction, since it is already provided by theuseStatehook.setKeysState((keysState = keys));