CSS media queries update by themselves, but a chart or map drawn by a script keeps its old colors when someone switches to dark mode. matchMedia() gives a script the same information, plus an event when it changes.
const dark = window.matchMedia("(prefers-color-scheme: dark)");
function applyTheme() {
chart.setTheme(dark.matches ? "dark" : "light");
}
applyTheme();
dark.addEventListener("change", applyTheme);
matchMedia() takes any media query and returns a MediaQueryList. Its matches property says whether the query applies right now, and its change event fires when that flips. I call the function once at startup and then on every change. On macOS with automatic appearance, that means the chart switches at sunset without a reload.
The same pattern works for other queries: (prefers-reduced-motion: reduce) to stop a carousel, or (min-width: 60rem) to switch a component between layouts without listening to every resize.
A compatibility note: older code uses dark.addListener(fn). MDN marks that method as deprecated; addEventListener("change", ...) works in Chrome 39, Firefox 55 and Safari 14 and later. Before Safari 14 only addListener existed, which is why you still see it in old snippets.
Further reading: MDN: Window.matchMedia(), MDN: MediaQueryList change event