개요
[1] useOptimistic
[2] reference
[1] useOptimistic
useOptimistic이란?
리액트 19 부터 지원하는 훅으로 optimistic update를 쉽게 구현할 수 있도록 해준다. 사용시 Concurrent Mode가 적용되서 nonblocking 방식으로 상태를 업데이트할 수 있다.
nonblocking과 Concurrent Mode에 대해 알고 싶다면 핵심만 뽑아서 정리했으니 아래의 포스트를 참고 바란다.
[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
'Frontend > React' 카테고리의 다른 글
[React] 다양한 로딩 전략과 캐싱을 구현한 이미지 컴포넌트 구현하기 (1) | 2025.03.15 |
---|---|
[React] useTransition, Concurrent Mode 쉽게 이해하기 (0) | 2025.03.09 |
[React] React Conference 2024 정리 (0) | 2024.05.20 |
[React] Custom Hooks (0) | 2023.09.18 |
[React] React.memo, useCallback, useMemo, Closure (0) | 2023.09.09 |