keepPreviousData (v4) / placeholderData: prev => prev (v5) giữ data trang trước khi paginate — tránh flash trắng; kết hợp với prefetch trang tiếp theo cho UX hoàn hảo. keepPreviousData là v3/v4 API, trong v5 thay bằng placeholderData: (previousData) => previousData (identity function).
- Khi queryKey thay đổi (page 1 → page 2), thay vì show loading + clear data cũ, React Query giữ nguyên data của page 1 trong khi fetch page 2 —
isPlaceholderData: truecho biết đang hiển thị data cũ. - UX impact lớn với pagination: user thấy page 1 vẫn hiển thị (có thể mờ đi để indicate loading), page 2 load xong thì replace — không có flash trắng.
- Kết hợp với prefetch để UX hoàn hảo:
useEffect(() => { if (!isPlaceholderData && hasNextPage) { queryClient.prefetchQuery({ queryKey: ['todos', page + 1], queryFn: () => fetchTodos(page + 1) }) } }, [data, page, isPlaceholderData, queryClient]). - Cũng hữu ích với filter/search: khi user gõ query search, giữ previous results trong khi tìm kiếm mới → không flash empty.
- Lưu ý: nếu dùng
selecttransform, previousData cũng đã qua select — types match đúng.
keepPreviousData (v4) / placeholderData: prev => prev (v5) keeps previous page data visible during pagination — no blank flash; combine with prefetching the next page for the best UX. keepPreviousData (v4) / placeholderData: keepPreviousData (v5) maintains the previous data on screen while new data is being fetched — preventing blank/loading states during transitions.
- Most useful for: Pagination — when changing pages, show current page data while next page loads instead of a blank state; Filtering — when applying filters, show current results while filtered results load; Any scenario where query key changes trigger a new fetch.
- In v5: placeholderData: (previousData) => previousData — receives the previous data as the first argument; isPlaceholderData is true while showing old data and fetching new.
- Example: useQuery({ queryKey: ['todos', page], queryFn: () => fetchTodos(page), placeholderData: keepPreviousData }) — import keepPreviousData from @tanstack/react-query.
- Combine with prefetching next page for the smoothest pagination experience.