본문 바로가기

개발

Optimistic Updates 원리의 이해

 

Optimistic Updates는 서버가 제대로 동작할 것을 낙관적으로 기대하며 response를 기다리지 않고 유저에게 바로 피드백을 주는 방식이다.

ex. 인스타그램의 좋아요 ❤️

리액트 쿼리의 useMutation()을 활용해 구현해보자.

const likeMutation = useMutation({
  mutationFn: async ({ postId, username, userAction }) => {
    if (userAction === USER_ACTION.LIKE_POST) {
      await likePost(postId, username);
    } else {
      await unlikePost(postId, username);
    }
  },
  onMutate: async ({ postId, username, userAction }) => {
    await queryClient.cancelQueries({
      queryKey: [QUERY_KEYS.LIKE_STATUS, postId],
    });
    await queryClient.cancelQueries({
      queryKey: [QUERY_KEYS.NUM_OF_LIKES, postId],
    });

    const prevLikeStatus = queryClient.getQueryData([
      QUERY_KEYS.LIKE_STATUS,
      postId,
      username,
    ]);
    const prevLikeCount = queryClient.getQueryData([
      QUERY_KEYS.LIKE_COUNT,
      postId,
    ]);

    queryClient.setQueryData(
      [QUERY_KEYS.LIKE_STATUS, postId, username],
      () => userAction === USER_ACTION.LIKE_POST
    );
    queryClient.setQueryData([QUERY_KEYS.LIKE_COUNT, postId], (prev) => {
      userAction === USER_ACTION.LIKE_POST ? prev + 1 : prev - 1;
    });

    return { prevLikeStatus, prevLikeCount };
  },
  onError: (err, { postId, username }, context) => {
    queryClient.setQueryData(
      [QUERY_KEYS.LIKE_STATUS, postId, username],
      context.prevLikeStatus
    );
    queryClient.setQueryData(
      [QUERY_KEYS.LIKE_COUNT, postId],
      context.prevLikeCount
    );
  },
  onSettled: (data, err, { postId, username }) => {
    queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.LIKE_STATUS, postId, username],
    });
    queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.LIKE_COUNT, postId],
    });
  },
});

 

onMutate
1. Optimistic Update를 적용하려는 데이터가 refetch로 인해 덮어씌워지는 것을 막기 위해 cancelQueries()를 실행하여 좋아요 관련 데이터를 받아 오지 않도록 함
2. 에러 발생 대비하여 롤백용 데이터 따로 저장
3. 원하는 값으로 쿼리 데이터 미리 변경
4. 롤백용 데이터 리턴


onError
롤백용 데이터를 context로 받아와서 context 값으로 쿼리 데이터 변경

onSettled
에러 여부와 상관없이 서버와 데이터를 동기화해주기 위해 좋아요 관련 데이터 쿼리를 invalidate

 

 

 

https://geuni620.github.io/blog/2024/4/20/query-optimistic/

 

예시로 살펴보는 낙관적 업데이트(optimistic updates) 2가지 방법

낙관적이네..

geuni620.github.io

 

설명이 잘 되어 있는 글!

 

 

아쉽게도 지금 하고 있는 프로젝트에 낙관적 업데이트를 적용해보기는 힘들었고...

애초에 좋아요 버튼처럼 진짜진짜 간단한 UI 외에는 굳이 적용할 필요가 있을까 싶다

 

 

'개발' 카테고리의 다른 글

React에서 GA4 세팅하기  (4) 2024.08.28
nvm  (0) 2024.07.18
github actions  (0) 2024.07.17
vercel 배포 시 주의사항 (vite)  (0) 2024.07.16
git hooks, husky를 활용한 초기 세팅 + Jira  (2) 2024.07.16