React 19부터 userTransition은 비동기 함수를 지원하여 isPending 상태를 별도로 관리할 필요가 없음. 비동기 전환이 진행될 때 isPending은 자동으로 true로 설정되고 완료되면 false로 변경된다. 이를 통하여 데이터 변경 시 에도 사용자는 끊김없는 상호작용이 가능함.
const handleAddToCart = () => {
startTransition(async () => {
try {
const cartItem = {
id: product.id,
title: product.title,
img: product.img,
price: product.price,
category: product.category,
discount: product.discount,
count: count,
}
await addCartData(cartItem)
handleClose()
navigate('/cart')
} catch (error) {
console.log(error)
}
})
}
<button onClick={handleAddToCart} disabled={isPending}>
{isPending ? '추가 중...' : '장바구니에 담기'}
</button>
useOptimistic은 UI를 낙관적으로 업데이트 할 수 있습니다.
API 요청 후 실제 응답이 오기전에 응답이 완료된 것 처럼 UI를 미리 업데이트를 할 수 있습니다.
낙관적으로 메세지를 일단 업데이트 후 실제 요청이 완료되면 UI가 다시 렌더링 됩니다. 이러한 점은 사용자 경험을 좋게합니다.
useOptimistic은 두개의 인자를 받는다.
initialState은 처음 상태를 말한다
reducer : 상태를 업데이트할 방법을 정의하는 함수
'use client'
import { useOptimistic, useState } from 'react'
export default function CommentForm({ initialComments }) {
const [comment, setComment] = useState('')
const [comments, setComments] = useState(initialComments)
const [optimisticComments, addOptimisticComment] = useOptimistic(
comments,
(prevComments, newComment) => [...prevComments, newComment]
)
const handleSubmit = async (e) => {
e.preventDefault()
const newComment = {
id: Date.now(), // 임시 ID
text: comment,
author: '민석',
}
addOptimisticComment(newComment)
const response = await fetch('/api/comments', {
method: 'POST',
body: JSON.stringify(newComment),
})
const savedComment = await response.json()
setComments((prev) => [...prev, savedComment])
setComment('')
}
return (
<div>
<form onSubmit={handleSubmit}>
<input value={comment} onChange={(e) => setComment(e.target.value)} />
<button type="submit">댓글 달기</button>
</form>
<ul>
{optimisticComments.map((c) => (
<li key={c.id}>
<strong>{c.author}</strong>: {c.text}
</li>
))}
</ul>
</div>
)
}
initialComments는 서버에서 받아온 기존 댓글 목록이다.
→ 페이지 진입 시 서버에서 댓글 데이터를 받아 comments 상태에 저장한다.
사용자가 입력창에 댓글을 입력하면 e.target.value를 통해 값이 comment에 저장된다.
handleSubmit이 실행되면:
사용자가 작성한 내용을 바탕으로 newComment 객체를 생성한다.
이 newComment를 addOptimisticComment(newComment)로 전달한다.\
이 순간 optimisticComments에 newComment가 추가되어,
서버에 요청을 보내기 전에 UI에 미리 표시된다.
→ 즉, 사용자는 서버 응답을 기다리지 않고 바로 새로운 댓글이 보이는 효과를 경험한다. (낙관적 UI)
서버에 실제로 댓글을 보내고(POST), 최신 댓글 목록을 다시 받아온다(GET)
이후 setComments를 통해 서버에서 받은 진짜 댓글 데이터를 다시 반영한다.
이번에 React19를 알아보며 내가 프로젝트에 쓸만한 것들만 정리해 보았다. 다음에는 더 다양한 기술과 변경된 점을 정리해보자