16
refの使い方アンチパターン
import { useState, useRef } from 'react';
export default function Counter() {
const [show, setShow] = useState(true);
const ref = useRef(null);
return (
{
setShow(!show);
}}>
Toggle with setState
{
ref.current.remove();
}}>
Remove from the DOM
{show &&
Hello world
}
);
}
左のコードでは、refを使ってDOMを直接操作(削除)
しています。
「Remove from the DOM」ボタンを押すと、下の
Hello Worldの表示は消えてしまいます。
この状態で、「Toggle with setState」ボタンを押すと
どうなる?