Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions frontend/src/components/common/RouteAnnouncer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
*/

import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useState } from "react";

/** Map pathname segments to human-readable page names. */
function pageTitle(pathname: string): string {
Expand Down Expand Up @@ -50,18 +50,19 @@ function pageTitle(pathname: string): string {
export function RouteAnnouncer() {
const pathname = usePathname();
const [announcement, setAnnouncement] = useState("");
const isFirstRender = useRef(true);
// Track the last announced pathname. Initialised to the current pathname so
// the very first render produces no announcement (the browser already
// announces initial page load).
const [lastPathname, setLastPathname] = useState(pathname);

useEffect(() => {
// Don't announce the initial page load — the browser already handles that.
if (isFirstRender.current) {
isFirstRender.current = false;
return;
}

const title = pageTitle(pathname);
setAnnouncement(`Navigated to ${title}`);
}, [pathname]);
// Adjusting state during render — React's recommended pattern for reacting
// to prop changes without an effect. React schedules an immediate re-render
// without committing the discarded one. Compatible with React Compiler
// (no `set-state-in-effect` violation).
if (pathname !== lastPathname) {
setLastPathname(pathname);
setAnnouncement(`Navigated to ${pageTitle(pathname)}`);
}

return (
<div
Expand Down
Loading