# Loading Events

Fetch events for the dates on screen as people navigate, and show a loading bar while they arrive.

Live example, interactive at https://calendarcn.xyz/docs/loading-events. Its source:

```tsx title="src/examples/range-loading-demo.tsx"
"use client";

import * as React from "react";
import {
  addDays,
  addMinutes,
  differenceInCalendarDays,
  eachDayOfInterval,
  format,
  isFriday,
  isWeekend,
} from "date-fns";
import { ChevronLeftIcon, ChevronRightIcon, RotateCwIcon } from "lucide-react";

import { cn } from "@/lib/utils";
import { AgendaView } from "@/components/agenda-view";
import { CalendarProvider, useCalendar } from "@/components/calendar-provider";
import { MonthView } from "@/components/month-view";
import { TimeGrid } from "@/components/time-grid";
import { YearView } from "@/components/year-view";
import { Button } from "@/components/ui/button";
import type {
  CalendarEvent,
  EventColor,
  ViewType,
  VisibleRange,
} from "@/components/calendar-types";

/** How long the pretend server takes to answer, in milliseconds */
const SERVER_DELAY_MS = 800;

/** Log entries kept on screen, newest first */
const MAX_LOG_ENTRIES = 8;

/** Day the pretend server counts from, so a day always gets the same events */
const SERVER_EPOCH = new Date(2026, 0, 1);

/** Views offered by the header's switcher, in display order */
const VIEW_OPTIONS: { value: ViewType; label: string }[] = [
  { value: "day", label: "Day" },
  { value: "week", label: "Week" },
  { value: "month", label: "Month" },
  { value: "year", label: "Year" },
  { value: "agenda", label: "Agenda" },
];

/** Meetings the pretend server spreads over weekdays */
const MEETINGS: {
  title: string;
  hour: number;
  minutes: number;
  color: EventColor;
}[] = [
  { title: "Design review", hour: 10, minutes: 60, color: "purple" },
  { title: "Customer call", hour: 11, minutes: 30, color: "green" },
  { title: "Lunch and learn", hour: 12, minutes: 60, color: "orange" },
  { title: "1:1", hour: 14, minutes: 30, color: "gray" },
  { title: "Planning", hour: 15, minutes: 60, color: "red" },
  { title: "Pairing", hour: 16, minutes: 90, color: "yellow" },
];

/** One `onVisibleRangeChange` call, as the log shows it */
interface RangeLogEntry {
  id: number;
  range: VisibleRange;
  status: "loading" | "loaded" | "cached";
  /** Events the server returned, once loaded */
  count: number | null;
}

export function RangeLoadingDemo() {
  const [events, setEvents] = React.useState<CalendarEvent[]>([]);
  const [pendingRequests, setPendingRequests] = React.useState(0);
  const [log, setLog] = React.useState<RangeLogEntry[]>([]);
  /** Ranges already requested: a tiny client-side cache, keyed by range */
  const fetchedRangesRef = React.useRef(new Set<string>());
  /** Range on screen, so Reload can fetch it again */
  const currentRangeRef = React.useRef<VisibleRange | null>(null);
  const nextLogIdRef = React.useRef(0);

  // The calendar calls this once on mount and whenever the visible dates
  // change: fetch the range unless it was fetched before
  const loadRange = React.useCallback((range: VisibleRange) => {
    currentRangeRef.current = range;
    const id = nextLogIdRef.current++;
    const addEntry = (entry: RangeLogEntry) =>
      setLog((prev) => [entry, ...prev].slice(0, MAX_LOG_ENTRIES));

    const key = `${range.start.toISOString()}/${range.end.toISOString()}`;
    if (fetchedRangesRef.current.has(key)) {
      addEntry({ id, range, status: "cached", count: null });
      return;
    }
    fetchedRangesRef.current.add(key);
    addEntry({ id, range, status: "loading", count: null });
    setPendingRequests((count) => count + 1);

    fetchEvents(range).then((fetched) => {
      // Keep what the calendar already has (and any edits to it), add the rest
      setEvents((prev) => {
        const knownIds = new Set(prev.map((event) => event.id));
        return [...prev, ...fetched.filter((event) => !knownIds.has(event.id))];
      });
      setLog((prev) =>
        prev.map((entry) =>
          entry.id === id
            ? { ...entry, status: "loaded", count: fetched.length }
            : entry,
        ),
      );
      setPendingRequests((count) => count - 1);
    });
  }, []);

  /** Forgets every fetched range and event, then loads the visible range again */
  const reload = React.useCallback(() => {
    fetchedRangesRef.current.clear();
    setEvents([]);
    setLog([]);
    if (currentRangeRef.current) loadRange(currentRangeRef.current);
  }, [loadRange]);

  return (
    <CalendarProvider
      events={events}
      onEventsChange={setEvents}
      onVisibleRangeChange={loadRange}
      loading={pendingRequests > 0}
    >
      {/* The log sits beside the calendar when there's room, below it otherwise */}
      <div className="@container h-full">
        <div className="flex h-full flex-col @2xl:flex-row">
          <div className="flex min-h-0 min-w-0 flex-1 flex-col">
            <CalendarHeader />
            <div className="min-h-0 flex-1">
              <CalendarBody />
            </div>
          </div>
          <RangeLog entries={log} onReload={reload} />
        </div>
      </div>
    </CalendarProvider>
  );
}

/** Title, today, previous and next, and the view switcher below them */
function CalendarHeader() {
  const { view, monthName, year, goToToday, goToPrev, goToNext, switchView } =
    useCalendar();

  return (
    <header className="flex flex-col gap-2 border-b px-3 py-2">
      {/* The switcher gets its own row: five views don't fit beside the
          title in the half of the example the calendar gets */}
      <div className="flex items-center gap-2">
        <h2 className="min-w-0 flex-1 truncate text-sm font-semibold">
          {monthName} {year}
        </h2>
        <Button variant="secondary" size="sm" onClick={goToToday}>
          Today
        </Button>
        <div className="flex items-center">
          <Button
            variant="ghost"
            size="icon-sm"
            aria-label={`Previous ${view}`}
            onClick={goToPrev}
          >
            <ChevronLeftIcon />
          </Button>
          <Button
            variant="ghost"
            size="icon-sm"
            aria-label={`Next ${view}`}
            onClick={goToNext}
          >
            <ChevronRightIcon />
          </Button>
        </div>
      </div>
      <div
        role="group"
        aria-label="View"
        className="flex items-center rounded-md bg-muted p-0.5"
      >
        {VIEW_OPTIONS.map((option) => (
          <button
            key={option.value}
            type="button"
            aria-pressed={view === option.value}
            onClick={() => switchView(option.value)}
            className={cn(
              "h-7 flex-1 rounded-sm px-2.5 text-xs font-medium text-muted-foreground transition-[color,background-color,box-shadow,scale] duration-150 ease-out outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 active:scale-[0.96] motion-reduce:active:scale-100",
              view === option.value &&
                "bg-background text-foreground shadow-xs dark:bg-input",
            )}
          >
            {option.label}
          </button>
        ))}
      </div>
    </header>
  );
}

/** The view the provider is on */
function CalendarBody() {
  const { view } = useCalendar();

  if (view === "month") {
    return <MonthView />;
  }

  if (view === "agenda") {
    return <AgendaView />;
  }

  if (view === "year") {
    return <YearView />;
  }

  return <TimeGrid view={view} scrollToHour={8} />;
}

interface RangeLogProps {
  entries: RangeLogEntry[];
  onReload: () => void;
}

/** Every range the calendar reported, and whether it came from the server or the cache */
function RangeLog({ entries, onReload }: RangeLogProps) {
  return (
    <aside className="flex h-44 shrink-0 flex-col border-t @2xl:h-auto @2xl:w-60 @2xl:border-t-0 @2xl:border-l">
      <div className="flex items-center justify-between gap-2 border-b px-3 py-2">
        <div className="min-w-0">
          <h3 className="truncate font-mono text-xs font-medium">
            onVisibleRangeChange
          </h3>
          <p className="text-[11px] text-muted-foreground">
            Newest first, end exclusive
          </p>
        </div>
        <Button
          variant="ghost"
          size="icon-sm"
          onClick={onReload}
          aria-label="Clear the cache and reload"
          title="Clear the cache and reload"
        >
          <RotateCwIcon />
        </Button>
      </div>
      <ul aria-label="Visible ranges" className="flex-1 overflow-y-auto p-1">
        {entries.map((entry) => (
          <li
            key={entry.id}
            data-testid="range-log-entry"
            data-start={format(entry.range.start, "yyyy-MM-dd")}
            data-end={format(entry.range.end, "yyyy-MM-dd")}
            data-status={entry.status}
            className="rounded-sm px-2 py-1.5"
          >
            <span className="block text-xs font-medium tabular-nums">
              {format(entry.range.start, "EEE, MMM d")} →{" "}
              {format(entry.range.end, "EEE, MMM d")}
            </span>
            <span className="block text-[11px] text-muted-foreground tabular-nums">
              {differenceInCalendarDays(entry.range.end, entry.range.start)}{" "}
              days · {describeStatus(entry)}
            </span>
          </li>
        ))}
      </ul>
    </aside>
  );
}

/** "Loading…", "12 events" or "From cache" */
function describeStatus(entry: RangeLogEntry): string {
  if (entry.status === "loading") return "Loading…";
  if (entry.status === "cached") return "From cache";
  return `${entry.count} events`;
}

/** Pretend API: answers after SERVER_DELAY_MS with the events in `range` */
function fetchEvents(range: VisibleRange): Promise<CalendarEvent[]> {
  const days = eachDayOfInterval({
    start: range.start,
    end: addDays(range.end, -1),
  });
  const events = days.flatMap(getServerEvents);
  return new Promise((resolve) => {
    setTimeout(() => resolve(events), SERVER_DELAY_MS);
  });
}

/**
 * The pretend server's events for one day: a standup and one or two meetings
 * on weekdays, a release every other Friday, a long run on some weekends.
 * Ids are stable, so loading a day twice never duplicates its events.
 */
function getServerEvents(day: Date): CalendarEvent[] {
  const seed = differenceInCalendarDays(day, SERVER_EPOCH);
  const dayKey = format(day, "yyyy-MM-dd");
  const at = (hour: number, minute = 0) =>
    new Date(day.getFullYear(), day.getMonth(), day.getDate(), hour, minute);

  if (isWeekend(day)) {
    if (modulo(seed, 3) !== 0) return [];
    return [
      {
        id: `${dayKey}-run`,
        title: "Long run",
        start: at(8),
        end: at(9, 30),
        color: "green",
      },
    ];
  }

  const events: CalendarEvent[] = [
    {
      id: `${dayKey}-standup`,
      title: "Standup",
      start: at(9, 30),
      end: at(9, 45),
      color: "blue",
    },
  ];
  // All-day events end at the start of their last day
  if (isFriday(day) && modulo(seed, 2) === 0) {
    events.push({
      id: `${dayKey}-release`,
      title: "Release",
      start: at(0),
      end: at(0),
      isAllDay: true,
      color: "purple",
    });
  }
  const picks = new Set([
    modulo(seed, MEETINGS.length),
    modulo(seed * 5 + 2, MEETINGS.length),
  ]);
  for (const index of picks) {
    const meeting = MEETINGS[index];
    events.push({
      id: `${dayKey}-meeting-${index}`,
      title: meeting.title,
      start: at(meeting.hour),
      end: addMinutes(at(meeting.hour), meeting.minutes),
      color: meeting.color,
    });
  }
  return events;
}

/** Remainder that stays positive for days before SERVER_EPOCH */
function modulo(value: number, divisor: number): number {
  return ((value % divisor) + divisor) % divisor;
}
```

The calendar doesn't fetch anything itself. `onVisibleRangeChange` tells you which dates are on screen, every time they change, so you can load the events for them. While you do, `loading` draws a thin bar under the day headers. In the preview, a pretend server answers after 800ms. Navigate, switch views or scroll sideways, and watch the log: a range seen before comes from the cache, with no bar.

## Usage

Keep the events in state, fetch them in `onVisibleRangeChange`, and pass `loading` while a request is in flight:

```tsx
import { CalendarProvider } from "@/components/calendar-provider";
import { WeekView } from "@/components/week-view";
import type { CalendarEvent, VisibleRange } from "@/components/calendar-types";

export function Schedule() {
  const [events, setEvents] = React.useState<CalendarEvent[]>([]);
  const [loading, setLoading] = React.useState(false);
  const latestRequest = React.useRef(0);

  const loadRange = React.useCallback(async (range: VisibleRange) => {
    const request = ++latestRequest.current;
    setLoading(true);
    const next = await getEvents(range.start, range.end); // your API
    // People may have moved on while this was loading
    if (request !== latestRequest.current) return;
    setEvents(next);
    setLoading(false);
  }, []);

  return (
    <CalendarProvider
      events={events}
      onEventsChange={setEvents}
      onVisibleRangeChange={loadRange}
      loading={loading}
    >
      <WeekView />
    </CalendarProvider>
  );
}
```

With a data library such as [TanStack Query](https://tanstack.com/query), keep the range in state, use it as the query key, and pass `isFetching` as `loading`. Save drags, resizes and edits in `onEventUpdate`, and update the query's cache so they stick.

```tsx
const [range, setRange] = React.useState<VisibleRange | null>(null);
const { data: events = [], isFetching } = useQuery({
  queryKey: ["events", range?.start.toISOString(), range?.end.toISOString()],
  queryFn: range ? () => getEvents(range.start, range.end) : skipToken,
  placeholderData: keepPreviousData,
});

<CalendarProvider
  events={events}
  onVisibleRangeChange={setRange}
  onEventUpdate={saveEvent}
  loading={isFetching}
>
  <WeekView />
</CalendarProvider>;
```

The [Calendar](/docs/components/calendar) block takes every `CalendarProvider` prop and passes it through, so `onVisibleRangeChange` and `loading` work on it the same way:

```tsx
<Calendar
  events={events}
  onEventsChange={setEvents}
  onVisibleRangeChange={loadRange}
  loading={loading}
/>
```

## The range

`start` is midnight at the beginning of the first visible day, and `end` is midnight after the last one, so `end` is exclusive. Both are in the viewer's time zone. With `timeZone` on the provider, they are the instants those midnights fall on in that zone.

| View   | Range                                                                   | Example, week of Thursday Jun 4 2026 |
| ------ | ----------------------------------------------------------------------- | ------------------------------------ |
| Day    | The day on screen                                                       | Jun 4 → Jun 5                        |
| Week   | `numberOfDays` days from the first column, 7 by default                 | May 31 → Jun 7                       |
| Month  | The whole six-week grid, days from the months before and after included | May 31 → Jul 12                      |
| Agenda | The 30 days it lists, from its first day                                | Jun 4 → Jul 4                        |
| Year   | The whole year, January 1 to the next January 1                         | Jan 1 2026 → Jan 1 2027              |

When weekends are hidden, day and week view report the weekdays they draw: a week runs from Monday to Friday, so the range ends on Saturday's midnight. Month view's range starts and ends on the first and last weekday it shows. The agenda's range keeps its weekend days; it only leaves them out of its list.

An event belongs in the range when it starts before `end` and ends after `start`:

```ts
const inRange = (event: CalendarEvent, range: VisibleRange) =>
  event.start < range.end &&
  (event.isAllDay ? event.end >= range.start : event.end > range.start);
```

> **All-day events**
>
> An all-day event's `end` is the start of its last day, so a one-day event has `start` equal to `end`. Compare its end with `>=`, or it drops off the first day of the range.

Read the range anywhere inside the provider with `useCalendar().visibleRange`, and the loading state with `useCalendar().loading`, for example to show a spinner in your own toolbar.

## When it fires

- Once after the view mounts.
- When the dates change: previous and next, today, `goToDate`, a view switch, a new `numberOfDays`, and month view's vertical scroll.
- During a sideways scroll in day and week view, once the scroll snaps to a day, not for every day it passes. For the days on screen mid-scroll, read `visibleDays`.
- Never twice in a row for the same range. Re-renders, edits and selection don't fire it, and neither does a view switch that's undone because the mounted view doesn't follow it.

A range can come back: going to next week and back reports this week again. Cache by range, as the preview does, or by day, so a range seen before skips the network.

## Loading bar

`loading` draws a 2px indeterminate bar along the bottom of the day headers in Day View, Week View and Month View, and along the top of Agenda View and Year View. It doesn't block anything: people can keep dragging, creating and navigating while events load. With reduced motion turned on, the bar holds still instead of sliding. The view is marked `aria-busy` while loading.

The bar is `CalendarLoadingBar` in `components/calendar-loading-bar.tsx`, and its animation is a `.calendar-loading-bar` class. Both come with [Calendar Core](/docs/components/calendar-core#installation), so every view you install has it.

## API Reference

The provider props and the range type. See [Calendar Core](/docs/components/calendar-core#api-reference) for the rest of the provider.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onVisibleRangeChange` | `(range: VisibleRange) => void` | – | Called with the dates the view draws: once after it mounts, then each time they change. Never twice in a row for the same range. |
| `loading` | `boolean` | `false` | Shows a thin progress bar under the day headers of every view. The calendar stays usable. |

### VisibleRange

| Field | Type | Description |
| --- | --- | --- |
| `start` | `Date` | Midnight that starts the first visible day. |
| `end` | `Date` | Midnight after the last visible day (exclusive). |
