Alexey Tseitlin
Alexey Tseitlin

Reputation: 1319

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

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

Upvotes: 2

Views: 116

Answers (4)

Siddharth Agrawal
Siddharth Agrawal

Reputation: 116

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

Upvotes: 2

MkMan
MkMan

Reputation: 2191

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.

Upvotes: 1

Leon_K
Leon_K

Reputation: 127

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>;
}

Upvotes: 1

Harry Mumford-Turner
Harry Mumford-Turner

Reputation: 924

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>;
}

Upvotes: 0

Related Questions