LoginSignup
9
2

More than 1 year has passed since last update.

【React】useStateを使ったら無限ループしたので、対処した。Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Posted at

症状

useStateを使用したら、無限ループが発生してしまいました。
翻訳すると、「再レンダリングが多すぎます。 React は、無限ループを防ぐためにレンダリングの数を制限します。」です。

error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Hoge.jsx
import React, {useState} from "react";

export const Hoge= () =>{
  const [count,setCount] = useState(0);

  const handleHoge= () =>  {
      setCount(count+1)
  }

  return(
    <div>
        <div>{count}回押された</div>
        <button onClick={handleHoge()}>HOGEButton</button>
    </div>
  )
}

解決策

Clickイベントをアローにしたら、無限ループ解決しました。
render内をアロー関数で書かないと、render時にuseStateが呼ばれてしまい、再びrenderされ、そこでもuseState→renderm→useState→render...というループに陥るみたいです。

Hoge.jsx
import React, {useState} from "react";

export const Hoge= () =>{
  const [count,setCount] = useState(0);

  const handleHoge= () =>  {
      setCount(count+1)
  }

  return(
    <div>
        <div>{count}回押された</div>
        <button onClick={() => handleHoge()}>HOGEButton</button>
    </div>
  )
}

参考

9
2
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
9
2