はじめに
この記事では、React 19 で新たに追加された useActionState
という hook で簡単な実装を行い、その動作を確認してみます。
開発環境
開発環境は以下の通りです。
- Windows 11
- VSCode
- JavaScript
- React 19.0.0-rc-cc1ec60d0d-20240607
- Vite 5.2.0
- Node.js 20.14.0
- npm 10.8.1
また、React 19 RC のインストール方法については、以下の記事に記載しています。
useActionState
の実装
useActionState(action, initialState, permalink?)
useActionState
では、アクションの実行、実行ステートの管理、アクションの結果の取得ができます。
App.jsx
import { useActionState } from "react";
function App() {
const [likeCount, formAction, isPending] = useActionState(async () => {
const response = await fetch("https://example.com/like", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ likeCount }),
});
const jsonResponse = await response.json();
return jsonResponse.likeCount;
}, 0);
console.log("🚀 ~ App ~ \nisPending:", isPending, "\nlikeCount:", likeCount);
return (
<form action={formAction}>
<strong>Like: {likeCount}</strong>
<hr />
<button type="submit" disabled={isPending}>
Like
</button>
</form>
);
}
export default App;
動作確認
Like ボタンをクリックすると、formAction
内の処理が実行されます。処理開始後、isPending
が true
になります。処理が完了すると、isPending
は false
になり、アクションの結果として、likeCount
の値が更新されます。
参考
関連記事