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?

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

TanStack Query は、React アプリで サーバーとのデータやり取りを効率よく管理 できるライブラリです。
主な特徴は次の 2 つ:

  • useQuery → データ取得(GET)
  • useMutation → データ更新(POST / PUT / DELETE)

この記事では、このうち useMutation に絞って「ざっくり概要」と「なぜ使うのか」を初心者向けに解説します。


useMutation とは?

  • サーバーにデータを送ったり更新したりするためのフック

  • 例:

    • Todo の新規作成(POST)
    • ユーザー情報の更新(PATCH / PUT)
    • データ削除(DELETE)

なぜ使うの?

1. 非同期処理をまとめて扱える

  • 「送信中かどうか」「成功したか」「失敗したか」を一括で管理できる
  • 成功時や失敗時のコールバックも用意されている
const mutation = useMutation({
  mutationFn: (newTodo: Todo) => axios.post('/todos', newTodo),
  onSuccess: () => console.log('作成成功!'),
  onError: () => console.log('エラー発生'),
});

2. キャッシュと連動できる

  • 成功後に invalidateQueries を呼べば一覧を自動で再取得できる
onSuccess: () => {
  queryClient.invalidateQueries({ queryKey: ['todos'] });
};

「データを更新したら UI も最新化」 が自動で回るのが便利。
自分も useMutation を知らないときは Global State(Zustand) を利用して更新作業しましたが、実装の楽さが全然違います


よくある使い方

function TodoForm() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (newTodo: Todo) => axios.post('/todos', newTodo),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    mutation.mutate({ title: '新しいTodo' });
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? '送信中…' : '追加'}
      </button>
      {mutation.isError && <p>エラーが発生しました</p>}
    </form>
  );
}

まとめ

  • TanStack Query は「取得は useQuery、更新は useMutation」と覚えると分かりやすい
  • useMutation は非同期処理の状態管理を楽にしつつ、キャッシュ更新も自動化できる
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?