본문 바로가기
매일 해내는 개발/React

[React] optimistic update(낙관적 업데이트)

by 해야지 2023. 3. 7.
반응형

React Query는 API 호출과 관련된 데이터를 캐시하고 관리하는 라이브러리이다. 이 라이브러리는 optimistic updates(낙관적 업데이트)를 지원하며, 이는 데이터를 서버로부터 성공적으로 업데이트하기 전에도 UI를 업데이트할 수 있도록 한다. optimistic updates는 요청을 보내기 전에 UI를 업데이트하는 기능이다. 예를 들어, 사용자가 게시물을 좋아요 했을 때, UI에서 즉시 좋아요 수가 증가하도록 할 수 있다. 이 때 서버로 요청을 보내기 전에 UI를 업데이트하는 것이 낙관적 업데이트이다.

낙관적 업데이트는 사용자 경험을 개선하고, 서버에서 응답을 받을 때까지 기다리지 않고 사용자에게 빠른 피드백을 제공할 수 있다. 하지만 요청이 실패하면 이전 상태로 되돌려야 하므로, 이를 처리하는 롤백 로직을 함께 구현해야 한다. 이러한 이유로 optimistic updates는 일부 상황에서만 사용하는 것이 좋다.

React Query에서 낙관적 업데이트를 수행하는 방법은 쿼리 객체의 `onMutate` 옵션을 사용하는 것이다

onMutate 함수는 useMutation 훅에서 설정할 수 있는 옵션 중 하나이며, API 호출 전에 실행되는 함수이다. 이 함수는 최적화된 업데이트를 위해 현재 데이터 캐시를 업데이트하거나, UI를 변경하는 등의 작업을 수행할 수 있다. onMutate 함수는 업데이트가 성공적으로 이루어지지 않았을 때 사용할 수 있는 rollback 메커니즘도 제공한다.

 

아래는 공식 문서의 예시 코드이다.

const queryClient = useQueryClient()

useMutation({
  mutationFn: updateTodo,
  // When mutate is called:
  onMutate: async (newTodo) => {
    // Cancel any outgoing refetches
    // (so they don't overwrite our optimistic update)
    await queryClient.cancelQueries({ queryKey: ['todos'] })

    // Snapshot the previous value
    const previousTodos = queryClient.getQueryData(['todos'])

    // Optimistically update to the new value
    queryClient.setQueryData(['todos'], (old) => [...old, newTodo])

    // Return a context object with the snapshotted value
    return { previousTodos }
  },
  // If the mutation fails,
  // use the context returned from onMutate to roll back
  onError: (err, newTodo, context) => {
    queryClient.setQueryData(['todos'], context.previousTodos)
  },
  // Always refetch after error or success:
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['todos'] })
  },
})

onMutate 콜백 함수에서 UI를 업데이트하고, setQueryData 함수를 사용하여 이전 데이터에서 업데이트한다. onError 콜백 함수에서는 에러가 발생했을 때 이전 데이터로 롤백한다. 이렇게 optimistic updates를 사용하면 좀 더 빠른 UI 업데이트를 제공할 수 있다.

출처

 

Optimistic Updates | TanStack Query Docs

When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In

tanstack.com

 

반응형

댓글