1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ReactでError Too many re-renders. React limits the number of renders to prevent an infinite loop.が出た時の対処方法

Last updated at Posted at 2023-02-10

エラーの背景

次はカウントが5の倍数になったら笑顔マークが出る処理にしていきます。

App.jsx
//省略
const App = () => {
  const [count, setCount] = useState(0); //[]で配列の分割代入 1つ目はstateとして使う変数名 2つ目はそのstateを変更するための関数 0で初期値を設定
  const [smileFace, setSmileFace] = useState(true); //smileの関数 レンダリングの処理

  const clickPlus = () => {
    //setCount(100); //プラスボタンを押すと100になる
    setCount(count + 1); //プラスボタンを押すと+1
  };


const clickSwitchSmileFace = () => {
    setSmileFace(!smileFace);
  };

  if (count % 5 === 0) {
    setSmileFace(true);
  } else {
    setSmileFace(false);
  }

//省略

すると

Error
Too many re-renders. React limits the number of renders to prevent an infinite loop.
index.js
6 > ReactDom.render(<App />, document.getElementById("root")); //レンダリング //rootはindex.htmlの<div id="root"></div>

のようなエラーが出てきました。
これはコンポーネント内で再レンダリングが起きすぎているというエラーです。
これはstateを変更していきます。

解決法

論理演算子を入れてレンダリングしすぎないようにしました。

App.jsx
const clickSwitchSmileFace = () => {
    setSmileFace(!smileFace);
  };

  if (count % 5 === 0) {
    smileFace|| setSmileFace(true);  //smileFaceがfalseなら右のtrueを返す
  } else {
    smileFace && setSmileFace(false); //smileFaceがtrueなら右のfalseを返す
  }

資料

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?