Mastering React Query V4! Easy, Fast, and Scalable Server State Management Library ~ Part 2
--
Do you know that 90% of React application only requires server state management library such as React Query instead of client state library such as Redux? With React Query, you don’t need to worry about performance optimization, scalable architecture, error handling, etc. Knowing those, Learning React query is a must
This series consists of 2 parts, make sure you check them both:
- Part 1
- Part 2
In the previous part, we discussed everything about queries to retrieve data. However, how about handling the rest of CRUD operations such as creating data, updating data, or deleting data. In this part, we will discuss those and some advanced features of React Query.
Mutation
Mutation refers to updating the data state in the server. This includes creating, updating, or deleting data. To do this, React query provides another hook for this called useMutation
. Mutation is much simpler than queries where the main component of mutation is just the mutation function and the other options are optional.
const { mutate, mutateAsync, isLoading } = useMutation({
mutationFn: (data) => {
return axios.post('/api/todos', data)
},
})
//to trigger
mutate({ name: 'todo1' })
//or
mutateAsync({ name: 'todo1' })
Similar to Queries, the best practice for mutation is to create a custom hook. For example
const useCreateTodo = () => {
return useMutation({
mutationFn: (data) => {
return axios.post('/api/todos', data)
},
})
}
There are 2 ways to handle actions after the mutation is called. First is by passing the options of onSuccess
, onError
, and onSettled
. For example:
const useCreateTodo = ({ onSuccess, onError }) => {
return useMutation({
mutationFn: (data) => {
return axios.post("/api/todos", data);
},
onSuccess: (data) => {
//do…