╱╱╭╮╱╱╱╱╱╱╭━━━╮╱╱╱╭╮╱╭╮╱╱╱╱╱╱ ╱╱┃┃╱╱╱╱╱╱┃╭━╮┃╱╱╱┃┃╱┃┃╱╱╱╱╱╱ ╱╱┃┣━━┳━━╮┃┃╱┃┣━╮╱┃╰━╯┣━━┳━╮╱ ╭╮┃┃╭╮┃┃━┫┃╰━╯┃╭╮╮┃╭━╮┃╭╮┃╭╮╮ ┃╰╯┃╭╮┃┃━┫┃╭━╮┃┃┃┃┃┃╱┃┃╭╮┃┃┃┃ ╰━━┻╯╰┻━━╯╰╯╱╰┻╯╰╯╰╯╱╰┻╯╰┻╯╰╯

Frontend/React

[React] useOptimistic 쉽게 이해하기

재안안 2025. 3. 9. 16:08

개요

[1] useOptimistic

[2] reference


 

[1] useOptimistic

 

useOptimistic이란?

  리액트 19 부터 지원하는 훅으로 optimistic update를 쉽게 구현할 수 있도록 해준다. 사용시 Concurrent Mode가 적용되서 nonblocking 방식으로 상태를 업데이트할 수 있다.

 

nonblockingConcurrent Mode에 대해 알고 싶다면 핵심만 뽑아서 정리했으니 아래의 포스트를 참고 바란다.

https://jaeano.tistory.com/entry/React-useTransition-Concurrent-Mode-%EC%89%BD%EA%B2%8C-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0

 

[React] useTransition, Concurrent Mode 쉽게 이해하기

개요[1] useTransition[2] concurrent mode[3] useTransition Details[4] reference [1] useTransition useTransitoin이란?  리액트 18에 추가된 훅으로 nonblocking 방식으로 상태(state)를 업데이트할 수 있게 해준다. nonblocking이

jaeano.tistory.com

 

 

optimistic update란,

  비동기 통신과 같은 대기 상황이 발생했을 때, 결과를 기다리지 않고 기대되는 결과를 미리 UI에 반영하는 기법이다. 실제 결과와 기대된 결과가 다르다면, 롤백과 같은 상황에 맞는 조취를 하면 된다.

 

 const [optimisticValue, update] = useOptimistic(
    state,
    // updateFn
    (currentState, optimisticValue) => {
      // merge and return new state
      // with optimistic value
    }
  );

 

useOptiistic의 기본 동작은 다음과 같다.

  `useReducer` 훅과 비슷하게 인자로 초깃 값과 diaptch 함수를 받아,  optimistic value의 초깃 값과 update 함수로 사용하고, update를 호출하는 순간 optimistic value의 값은 바뀌게 된다.

 

  약간의 주의 사항으로 useOptimistic을 사용하면 새로운 상태가 만들어 지기 때문에 source of truth를 유지하는 방식으로 설계하는 것이 중요하다.

 

아래와 같이 사용할 수 있다.

 

function LikeButton({ likes, setLikes }) {
  const [optimisticLikes, dispatch] = useOptimistic(initialLikes, (state, action) => {
    switch (action.type) {
      case 'increment':
        return state + 1;
      case 'rollback':
        return action.payload;
      default:
        return state;
    }
  });

  const handleLike = () => {
    dispatch({ type: 'increment' });
    
    updateLikeCountOnServer()
    	.then(() => setLikes(optimisticLikes))
    	.catch(() => dispatch({ type: 'rollback', payload: likes - 1 }))
  };

  return (
    <button onClick={handleLike}>
      좋아요 {optimisticLikes}
    </button>
  );
}

 


 

[2] reference

 

https://react.dev/reference/react/useOptimistic

 

useOptimistic – React

The library for web and native user interfaces

react.dev

 

https://ko.react.dev/reference/react/useOptimistic

 

useOptimistic – React

The library for web and native user interfaces

ko.react.dev