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?

React Hook "useEffect" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.エラーが出る

1
Posted at

はじめに

Reactでコードを書いていた際にエラーが発生しました。
原因と解決策を記録として残します。

問題

useState や useEffect をコンポーネント関数の外に書いたとき発生しました。

React Hook "useEffect" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.
React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.

解決方法

「useState」 と 「useEffect」 を 「function App() 」の内側に移動したら解消しました。

Reactは内部でHooksの呼び出し順序を使って状態を管理しているため、コンポーネント外での呼び出しは動作が保証できず、禁止されているようです。

修正前

//  NG:関数コンポーネントの外
const [games, setGames] = useState<Game[]>([]);

useEffect(() => { ... }, []);

function App() {
  return <></>;
}

修正後

//  OK:関数コンポーネントの内側
function App() {
  const [games, setGames] = useState<Game[]>([]);

  useEffect(() => { ... }, []);

  return <></>;
}

おわりに

今まで何となくそうゆうものだと思って、関数コンポーネントの内側にHooksを記載していました。なぜ関数コンポーネントの内側にHooksを書かないといけないのを理解するいい機会になりました!

参考

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