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

初めてのJotaiで無限ループを起こしてPCをアチアチにした

Last updated at Posted at 2025-04-25

初めてJotaiを使用したときに無限ループが発生して焦ったので原因と解決策

Jotaiとは?

Reactで使用可能な状態管理ライブラリです。

useStateを使用すると発生するpropsのバケツリレーなどを回避できます。
facebookが開発をしていたRecoiの開発が完全に終了してしまったので、使い方が似てる?Jotaiが注目されています。
Redux等に比べて非常にシンプルで、useStateと同じような感覚で使用することが可能です。
そして作者が日本人です。

何が起きたか

以下のコードで無限ループが発生しました

import { atom, useAtom } from "jotai";
import "./App.css";

function App() {
  const countAtom = atom(0);
  const [count, setCount] = useAtom(countAtom);

  const handleClick = () => setCount((prev) => prev + 1);

  return (
    <>
      <p>{count}</p>
      <button onClick={handleClick}>+1</button>
    </>
  );
}

export default App;

原因

const countAtom = atom(0)をAppコンポーネントの内部で定義しているのが原因です。

今回の場合以下の流れで無限にloopします。
1 countAtomが新規に作成される
2 useAtomで新規に作成したcountAtomを使用する
3 再レンダリングが発生する
4 1に戻る

レンダリングの度に新しいatomを生成するため状態を保つことができず無限loopします。

解決策

atomをcomponentの外で定義します。

import { atom, useAtom } from "jotai";
import "./App.css";

const countAtom = atom(0);  // Component外へ

function App() {
	const [count, setCount] = useAtom(countAtom);  
	...
}

export default App;

なんか急に動作が重くなった、めっちゃPCが熱いという時は無限loopが起きているかも?
昔firebaseに無限ループが起き

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