admin管理员组

文章数量:1122846

I'm implementing a filtered list with pagination using React Query, and I'm experiencing a UI flicker when filters change. This happens because the page needs to reset to 1 when applying new filters.

// Query hook
export function usePatients({
  initialData,
  filters,
  skip,
  take,
}: {
  initialData?: TFetchResponse<Patient>;
  skip?: number;
  take?: number;
  filters?: PatientFilters;
}) {
  return useQuery({
    queryKey: ['patients', { skip }, { take }, { filters: JSON.stringify(filters) }],
    queryFn: async () => {
      const response = await patientFindManyAction({
        skip,
        take,
        filters,
      });

      if (!response || !response.data) throw new Error('Something went wrong');
      return response.data;
    },
    placeholderData: (previousData) => previousData ? previousData : initialData,
  });
}

// Usage in component
function PatientList() {
  const [page, setPage] = useState(1);
  const [filters, setFilters] = useState<PatientFilters>();
  const pageSize = 10;

  // When filters change, we need to reset to page 1
  useEffect(() => {
    setPage(1);
  }, [filters]);

  const { data, isLoading } = usePatients({
    skip: (page - 1) * pageSize,
    take: pageSize,
    filters
  });

  return (
    // ... rendering logic
  );
}

The Issue The sequence causing the flicker: 1. User applies new filter 2. Query starts fetching with new filters 3. Page state resets to 1 4. UI shows page 1 of OLD results while waiting 5. New filtered results arrive and replace the view This creates a jarring user experience where they briefly see the wrong data.

How can I prevent showing the old data with page 1 while the new filtered data is loading?

What's the correct pattern for handling this scenario with React Query?

本文标签: React Query Prevent flickering when filters changeStack Overflow