🇺🇸
Continuing my previous post about React Query, today I bring the two main hooks: useQuery and useMutation:
useQuery:
- Used for data fetching.
- Main configurations:
-
queryKey: The information key, which uniquely identifies the data you are fetching. -
queryFn: The asynchronous function that makes the API request, returns the data, and populates the cache.
-
- How it works:
- When we need to return data,
useQuerychecks for the existence of the data in theQueryCacheusing thequeryKey. - If the data exists:
useQueryreturns the data directly from the cache, avoiding unnecessary API requests. - If the data does not exist: The
queryFnis activated, making the API request, returning, and saving the data to theQueryCache.
- When we need to return data,
useMutation:
- Used for operations that modify data (POST, PUT, PATCH, DELETE).
- Main configurations:
-
mutationFn: Asynchronous function that sends the request to the API, performing the creation, update, or deletion operation on the server. -
onSuccess: Callback function that allows you to perform specific actions when the mutation is successful, such as updating the cache or displaying a confirmation message. -
onError: Callback function that allows you to handle errors in a personalized way, displaying error messages or performing other recovery actions. -
invalidateQueries: Function that makes the data obsolete within the cache, because we changed the data on the server.
-
- How it works:
- The
mutationFnfunction is executed, sending the request to the API. - After the request is completed, the
onSuccessandonErrorcallbacks are called, depending on the result of the operation. - If the mutation changes data that is already in the cache,
invalidateQueriesshould be used withinonSuccessto make the data obsolete and ensure that the cache is updated throughuseQuery
- The
🇧🇷
Continuando meu post anterior sobre React Query, hoje trago os dois principais hooks: useQuery e useMutation:
useQuery:
- Utilizado para buscas de dados
-
Configurações principais:
-
queryKey: A chave da informação, que identifica de forma única os dados que você está buscando. -
queryFn: A função assÃncrona que realiza a requisição à API e retorna os dados e alimenta o cache.
-
-
Funcionamento:
- Quando precisamos retornar um dado, o
useQueryverifica a existência do dado noQueryCachepor meio daqueryKey. - Caso o dado exista:
- O
useQueryretorna os dados diretamente do cache, evitando requisições desnecessárias à API.
- O
- Caso o dado não exista:
- A
queryFné ativada, fazendo a requisição à API, retornando e salvando o dado noQueryCache.
- A
- Quando precisamos retornar um dado, o
useMutation:
- Utilizado em operações que modificam os dados (POST, PUT, PATCH, DELETE).
-
Configurações Principais:
-
mutationFn: Função assÃncrona que envia a requisição para a API, realizando a operação de criação, atualização ou exclusão no servidor. -
onSuccess: Função de callback que permite executar ações especÃficas quando a mutação é bem-sucedida, como atualizar o cache ou exibir uma mensagem de confirmação. -
onError: Função de callback que permite tratar erros de forma personalizada, exibindo mensagens de erro ou executando outras ações de recuperação. -
invalidateQueries: Função que torna os dados obsoletos dentro do cache, pois alteramos os dados no servidor
-
-
Funcionamento:
- A função
mutationFné executada, enviando a requisição para a API. - Após a conclusão da requisição, os callbacks
onSuccess,onErrorsão chamados, dependendo do resultado da operação. - Caso a mutação altere dados que já estão no cache, o
invalidateQueriesdeve ser usado dentro doonSuccesspara tornar o dado obsoleto garantir que o cache seja atualizado por meio do useQuery.
- A função


Top comments (0)