React: Invalid hook call
Reactフックが不正な場所で呼び出された際のエラー原因と解決策
概要
Reactフックがコンポーネント外や条件分岐内で呼び出された際に発生するエラーです。
エラーメッセージ
``` Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app ```
原因
- 複数のReactインスタンス: npm linkやモノレポでの重複
- Reactバージョンの不一致: react と react-dom のバージョン違い
- フックのルール違反: 条件分岐やループ内での呼び出し
- 通常の関数からの呼び出し: コンポーネント外での使用
解決策
1. Reactの重複を確認
```bash npm ls react npm ls react-dom
重複がある場合
npm dedupe ```
2. バージョンを統一
```json { “dependencies”: { “react”: “^18.2.0”, “react-dom”: “^18.2.0” }, “resolutions”: { “react”: “18.2.0”, “react-dom”: “18.2.0” } } ```
3. フックのルールを守る
```jsx // 悪い例 function MyComponent({ isLoggedIn }) { if (isLoggedIn) { const [user, setUser] = useState(null); // NG: 条件分岐内 } }
// 良い例 function MyComponent({ isLoggedIn }) { const [user, setUser] = useState(null); // OK: トップレベル
if (!isLoggedIn) { return ; } return ; } ```
4. カスタムフックを正しく作成
```jsx // 悪い例: 通常の関数 function getUser() { const [user, setUser] = useState(null); // NG return user; }
// 良い例: use プレフィックス function useUser() { const [user, setUser] = useState(null); return user; } ```
よくある間違い
- ライブラリ開発時にpeerDependenciesを設定しない
- npm linkでReactが重複
- クラスコンポーネントでフックを使用
関連エラー
関連エラー
React の他のエラー
この記事は役に立ちましたか?