Skip to main content

useMeta

Overview

The useMeta hook is a custom React hook for dynamically managing <meta> tags in the <head> of an HTML document. It allows you to set or update meta tags based on component lifecycle and cleans them up when the component unmounts.

Importing

To use the useMeta hook, import it:

import useMeta from './path/to/useMeta'

Hook Signature

useMeta(
name: string,
content: string
): void

Parameters

  • name: A string representing the name attribute of the meta tag.
  • content: A string representing the content attribute of the meta tag.

Returns

This hook does not return any values; it manages the <meta> tag in the document's <head>.


How It Works

  1. Creation:
    • Creates a <meta> element with the specified name and content attributes.
  2. Append:
    • Appends the <meta> tag to the <head> of the document when the component mounts.
  3. Cleanup:
    • Removes the <meta> tag from the <head> when the component unmounts.

Example Usage

Basic Example

import React from 'react';
import useMeta from './path/to/useMeta';

const PageWithMeta: React.FC = () => {
useMeta('description', 'This is a custom description for the page.');

return (
<div>
<h1>Page with Meta Tag</h1>
<p>Check the page source to see the dynamically added meta tag.</p>
</div>
);
};

export default PageWithMeta;

Explanation

  1. Meta Tag Addition: When the PageWithMeta component mounts, the useMeta hook adds a <meta> tag with name='description' and the specified content to the <head>.
  2. Cleanup: When the component unmounts, the <meta> tag is removed.

Dynamic Meta Tags Example

import React, { useState } from 'react';
import useMeta from './path/to/useMeta';

const DynamicMetaExample: React.FC = () => {
const [metaContent, setMetaContent] = useState('Initial content');

useMeta('description', metaContent);

return (
<div>
<h1>Dynamic Meta Example</h1>
<button onClick={() => setMetaContent('Updated content')}>Update Meta Content</button>
</div>
);
};

export default DynamicMetaExample;

Explanation

  1. Dynamic Updates: The metaContent state updates dynamically, and the useMeta hook ensures that the <meta> tag content reflects the new value.
  2. Reactivity: React automatically re-runs the useEffect when the state changes.

Best Practices

  • Avoid Duplicates: Ensure that name attributes are unique to prevent adding duplicate <meta> tags.
  • Static Meta Tags: For static meta tags, define them directly in the HTML <head> to reduce unnecessary renders.
  • Dynamic Tags: Use this hook for meta tags that need to change based on component state or props.

Notes

  • Meta tags are crucial for improving SEO and providing contextual information about your page.
  • The hook ensures clean handling of meta tags, preventing memory leaks or tag duplication.

Contributing

If you encounter issues or have suggestions for improving the useMeta hook, feel free to contribute or report an issue on the repository.