ReactHooksのルール
フックを呼び出すのは React の関数内のみ
rendering毎に、同じhooksを同じ順序で呼び出す必要がある
「フックを呼び出すのはトップレベルのみ
ref」というルールは、それを規定するためにある
例えば、トップレベルでなくとも、順序が変わらないのであれば不具合は生じない
自明な例
ts let [count, setCount] = [null, null];
if (true) {
[count, setCount] = useState(100);
}
ちなみに途中で呼ばれるhookが変わるような以下の例でも実行時エラーは生じない
ただ、予測される挙動とは異なる
x
がincrementされていき、 x > 10
を満たしても、常に下の方が呼ばれる
tsconst [x, setX] = useState(0);
let [count, setCount] = [null, null];
if (x > 10) {
[count, setCount] = useState(100);
} else {
[count, setCount] = useState(50);
}
<button onClick={() => setX(c => c + 1)}>+</button>
こんなふうに、customHookにして、内部でいくつかのhookを呼んでいると実行時エラーになる
ts// 特に意味もなくuseRef, useEffectを呼んでいるCustom Hook
const useRenderCount = () => {
const [count, setCount] = useState(0);
const ref = useRef(1);
useEffect(() => {
})
return [count, setCount];
}
tslet [count, setCount] = [null, null];
if (x > 10) {
[count, setCount] = useState(100);
} else {
[count, setCount] = useRenderCount(); // ここをcustom hookに。
}