Skip to content
Optimistic UI프로젝트

Optimistic UI Update With useSWR

1 min readProjectsMoved from my Tistory blogRead the Korean original

Among the things I studied today through Nomad Coders (a Korean online coding course site), I learned about Optimistic UI Update.

What is Optimistic UI Update?

For example, say you send a Post request to the backend and want to update the screen with the updated data.

Until now, you've probably often sent another Get request and updated the screen with the data you got back.

When you want to send the Post request and immediately show the screen as if the data had already changed (sort of?), that's what Optimistic UI Update is for.

I implemented Optimistic UI Update with the mutate function in useSWR.

ts
  const { data, mutate } = useSWR<ItemDetailResponse>(
    router.query.id ? `/api/products/${router.query.id}` : null
  );
  
  const onFavClick = () => { // like feature
    toggleFav({}); // like request to the backend
    if (!data) return;
    mutate({ ...data, isLiked: !data.isLiked }, false); // Think of it as passing, through mutate, the data you expect to get back.
  };

Also, the first argument to mutate is the data you expect to receive, and the second, a boolean, decides whether to Get the data again.

Nomad Coders - Carrot Market
Figure 1. Nomad Coders - Carrot Market

At work we use React-Query, but useSWR seems really useful too.

  • #Optimistic UI Update
  • #useSWR
  • #Nomad Coders
  • #Carrot Market
  • #frontend developer Sungjun Um

More in Projects