Adding an object to useState in react. Error "Too many re-renders"

Viewed 84

As soon as I add an object to "setTitle" I get an error. Setting the object in "useState()" works.

import React, { useState } from "react";

export default function App() {
  const [title, setTitle] = useState({});
  setTitle({
    "somthing": "dfgsf"
  });
  return <p>df</p>;
}

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

Live: https://codesandbox.io/s/custom-hook-playground-bzt6s?file=/src/App.js

4 Answers

When component will mount for the first time, "setTitle" function will be called which will update the state.

When state updates, re-rendering happens, thus "setTitle" function will be called again, triggering an infinite loop

Solution:

Use "useffect" or some other function to update the state

You must use initialState when defining the state. You can then add an onClickin order to change the title state using setState

This is the right way:

import React, { useState } from "react";

export default function App() {
  const [title, setTitle] = useState({"somthing": "dfgsf"});

  function buttonHandler() {
    setTitle({
        "somthing": "dfgsf"
      });
      console.log(title)
  }
  return <button onClick={buttonHandler}>sdf</button>;
}

This is happening because state updates cause a re-render. Because you're updating the state unconditionally the component keeps re-rendering indefinitely. This doesn't have anything to do with initial state.

useState takes an initialState as it's argument.

Try something like this?

export default function App() {
  const [title, setTitle] = useState("My Initial Title");
  return <p onClick={() => setTitle('New')}>{title}</p>;
}
Related