Files
AndreaSlopFotografie/web/src/components/Hero/useHero.ts
T
SluijsensandClaude Sonnet 5.5 3d7bb2d4a6 Hero: keep the plain HTML region after hydration, add the slider around it
Replacing the region at hydration made new nodes (a late LCP candidate). The first photo, the title and the buttons now stay; the other slides, arrows and controls are added on top.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 17:39:06 +01:00

57 lines
2.2 KiB
TypeScript

import { useEffect, useMemo, useState } from 'react';
import {
loadFromApi,
type LoadJson,
} from '@/components/PackagesProvider/PackagesProvider';
import useHydrated from '@/hooks/useHydrated';
import { hostCmsData } from '@/lib/cmsData';
import { mapHero, type HeroData } from '@/lib/hero';
const HERO_PATH = '/api/v1/hero';
const TIMEOUT_MS = 8000;
// The hero to show: the one in the data block the CMS host wrote, else the
// one the API gives, else the baked one. Failing safe is the rule: a missing
// block, a network error, a 204, a time-out or an answer that cannot be used
// leaves the baked hero on screen. The block is only read after hydration,
// so the first render equals the prerendered HTML.
export default function useHero(
baked: HeroData,
load: LoadJson = loadFromApi,
): { hero: HeroData; regionHero: HeroData } {
const hydrated = useHydrated();
const fromBlock = useMemo(() => {
const block = hydrated ? hostCmsData(document) : null;
return block?.hero === undefined ? null : mapHero(block.hero);
}, [hydrated]);
const [fetched, setFetched] = useState<HeroData | null>(null);
useEffect(() => {
// The host sent the data: nothing to ask
if (hostCmsData(document)) return;
const controller = new AbortController();
const { signal } = controller;
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
load(HERO_PATH, signal)
.then((answer) => {
const mapped = mapHero(answer);
if (mapped && !signal.aborted) setFetched(mapped);
})
.catch(() => undefined)
.finally(() => clearTimeout(timer));
return () => {
clearTimeout(timer);
controller.abort();
};
}, [load]);
// regionHero is what the plain HTML region of the page holds: the baked
// hero, or the one the API gave. The block of the host does not count: the
// host wrote that region itself and it must not be written over (that
// would replace the photo the browser has painted).
return {
hero: fromBlock ?? fetched ?? baked,
regionHero: fetched ?? baked,
};
}