Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Intermediate

Mutations

Definition

Endpoints defined in RTK Query that are used for WRITE operations (changing data on the server). Typically maps to `POST`, `PUT`, `PATCH`, or `DELETE` requests.

Explain Like I'm New

A Mutation is when you alter data. 'Update my profile picture.' Unlike Queries (which just return data automatically), Mutations return a 'trigger' function that you have to manually call when the user clicks a submit button.

Real World Example

Submitting a login form. You define a `login: builder.mutation({...})` endpoint, use the `useLoginMutation()` hook, and call `login(credentials)` when the form submits.

Common Use Cases

  • •Submitting forms
  • •Deleting items
  • •Updating records

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Are Mutations automatically cached by RTK Query like Queries are?

intermediate

  • What two things does a `use[Name]Mutation` hook return in its array?

Flash Cards

Question

Automatically cached?

Click to reveal answer
Answer

No. Because Mutations change data, they are not cached. In fact, Mutations are usually used to INVALIDATE the cache of previous Queries.

Question

What does it return?

Click to reveal answer
Answer

It returns a tuple (array). The first item is the `trigger` function (used to fire the request). The second item is an object containing `{ isLoading, error, data }`.