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

Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.(メモ)

Posted at

エラー内容

下記のエラーは、別コンポーネントをレンダリングしたい時、他の値を返す可能性のある条件の後にhooksを使用すると発生します

Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

エラーが発生する例

import React, { useState } from 'react'

export default function App() {
  const [loading, setLoading] = useState()

  // 👇エラー発生原因
  if (loading) {
    <p>Loading...</p>
  }
  const [count, setCount] = useState(0)

  return (
    <div>
      <span>{count}</span>
      <button onClick={(e) => setCount(count => count + 1)}>ボタン</button>
    </div>
  )
}

正常なコード

useStateの下に置く。
コンポーネントがレンダリングされるたびにReactフックが同じ順序で呼び出されるようにする必要があるため、これによりエラーが解決されます。ループ、条件、またはネストされた関数内でフックを使用できない。

import React, { useState } from 'react'

export default function App() {
  const [loading, setLoading] = useState()
  const [count, setCount] = useState(0)

  // 👇
  if (loading) {
    <p>Loading...</p>
  }

  return (
    <div>
      <span>{count}</span>
      <button onClick={(e) => setCount(count => count + 1)}>ボタン</button>
    </div>
  )
}

参照
Rules of Hooks

2
0
0

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