-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
HeadContent.mjs
42 lines (35 loc) · 1.11 KB
/
HeadContent.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// @ts-check
import {
createElement as h,
Fragment,
useCallback,
useEffect,
useState,
} from "react";
/** @type {Promise<void> | null} */
let updatePromise;
/**
* React component that renders the managed document head tags in response to
* head manager `update` events.
* @param {object} props Props.
* @param {import("./HeadManager.mjs").default} props.headManager Head manager.
*/
export default function HeadContent({ headManager }) {
const [content, setContent] = useState(() => headManager.getHeadContent());
const onUpdate = useCallback(() => {
// Handle close together updates as a batch to reduce renders.
const promise = (updatePromise = Promise.resolve().then(() => {
if (promise !== updatePromise) return;
updatePromise = null;
setContent(headManager.getHeadContent());
}));
}, [headManager]);
useEffect(() => {
headManager.addEventListener("update", onUpdate);
return () => {
headManager.removeEventListener("update", onUpdate);
};
}, [headManager, onUpdate]);
// Fragment is only to make TypeScript happy.
return h(Fragment, null, content);
}