react-metatags-hook
Version:
React Hook to manage html meta tags
55 lines (54 loc) • 2.85 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMetaTags = void 0;
const react_1 = require("react");
const state_1 = require("./state");
const dom_1 = require("./render/dom");
// Subscribes to store changes and update DOM
state_1.metaTagsStore.subscribe((metas) => (0, dom_1.updateDom)(metas, 50));
// NOTE: useEffects runs from the inner component up to the root, but we want metatags
// to be merged with a logic of letast rendered components to "win" over the previous ones.
// So the idea is:
// - when a component mounts for the first time we define a unique ID and timestamp for each
// "instance" of its useMetaTags usage
// - in a useEffect we "register" this instance in the store using the id and the timestams:
// even if the useEffects will run with another order (from the inner to the outer component),
// the timestamp we generated at the first render of the component will be used to merged
// meta tags definitions in the correct order
// - everytime a dependency changes, the meta tags config used to replace the meta tags
// definitions in the registered "instance" in the store
// - When a component is unmounted, the instance is deregistered from the store, and its
// meta tags are removed from the result of the final merge
const useMetaTags = (config, dependencies) => {
const hookInstanceId = (0, react_1.useRef)(Symbol());
const hookInstanceTs = (0, react_1.useRef)(Date.now());
// NOTE: When running on the server, effects doesn't run, so here
// metatags are saved within the render function
if (typeof window === 'undefined') {
state_1.metaTagsStore.registerInstance(hookInstanceId.current, hookInstanceTs.current);
state_1.metaTagsStore.setInstanceMetaTags(hookInstanceId.current, (0, state_1.parseMetaConfig)(config));
}
(0, react_1.useEffect)(() => {
const deregisterInstance = state_1.metaTagsStore.registerInstance(hookInstanceId.current, hookInstanceTs.current);
return () => {
deregisterInstance();
};
}, []);
(0, react_1.useEffect)(() => {
const newMetaTagsModel = (0, state_1.parseMetaConfig)(config);
state_1.metaTagsStore.setInstanceMetaTags(hookInstanceId.current, newMetaTagsModel);
// NOTE: we want to regenerate the meta tags only when the explicit dependencies change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dependencies]);
};
exports.useMetaTags = useMetaTags;
/**
* @deprecated Do not use the default export from 'react-metatags-hook', it will be removed in a future release.
*
* Please use the named export `useMetaTags`.
*
* e.g. `import { useMetaTags } from 'react-metatags-hook'`
*/
exports.default = (config, dependencies) => {
(0, exports.useMetaTags)(config, dependencies);
};
;