Component Patterns

This page covers how to effectively use Redux and RTK Query in React components, including hooks, optimization patterns, and best practices.

Basic Query Usage

Use generated hooks from RTK Query endpoints:

import { useGetParcelByCoordsQuery } from '@/features/land/land.client';

function ParcelCard({ x, y }: { x: number; y: number }) {
  const { data, isLoading, isError, error } = useGetParcelByCoordsQuery({ x, y });

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error: {error.toString()}</div>;
  if (!data) return null;

  return (
    <div>
      <h2>{data.name || `Parcel ${x},${y}`}</h2>
      <p>Owner: {data.owner}</p>
    </div>
  );
}

Optimizing Re-renders with selectFromResult

Narrow the result to only the fields you need:

Conditional Queries with skip

Skip queries when arguments aren't ready:

Polling for Real-time Updates

Lazy Queries

Trigger queries manually instead of on component mount:

Mutation Usage

Basic Mutation

Mutation with Feedback

Using Slice State

Access slice state with useAppSelector:

Combining Multiple Queries

Derived State with Selectors

Dispatching Actions

Entity Adapter Selectors

Prefetching Data

Prefetch data before navigation for faster UX:

Manual Cache Management

Handling Query States

Form Integration

Best Practices

1. Use Typed Hooks

2. Handle All Query States

3. Use .unwrap() for Mutations

4. Narrow Results with selectFromResult

5. Avoid Selecting Entire Slices

Next Steps

Last updated