エラー内容
- Warning: React has detected a change in the order of Hooks called by...
- Error: Rendered more hooks than during the previous render.
原因1
エラーにあるように、前回のレンダリングに比べてHooksの数が異なる
例えば以下の場合、10回クリックするとHooksの数が1から2になってしまう
10回クリックするとエラーになる
function App() {
const [count, setCount] = useState(0);
if (count < 10)
return (
<button type="button" onClick={() => setCount((count) => count + 1)}>
count is: {count}
</button>
);
const [] = useState(); // ダミー
return <div>You clicked more than 10 times !</div>;
}
Hooksは関数の初めに定義しておく
エラーにならない
function App() {
const [count, setCount] = useState(0);
const [] = useState();
if (count < 10)
return (
<button type="button" onClick={() => setCount((count) => count + 1)}>
count is: {count}
</button>
);
return <div>You clicked more than 10 times !</div>;
}
原因2
関数形式でコンポーネントを呼んでいる
hooksは使えない
return SomeComponent(someProps)
ちゃんとcreateElementをするか、jsxで記述する
createElementを使う
import {createElement} from 'react';
...
return createElement(SomeComponent, someProps)
...
jsxを使う
import React from 'react';
...
return <SomeComponent {...someProps} />
...