What is the purpose of react-helmet?

A major benefit or react-helmet is when you have multiple components in a tree with <head> tags, and you have <meta> tags with the same attributes/values.

For instance, if on your index page component you have:

const html = renderToString(<App />);
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="This is the index page description"> 
    <title>A Cool Index Page</title>
  </head>
</html>

But then on a leaf page component, you also have a <head> tag containing meta tags:

<html>
  <head>
    <meta name="description" name="This is the unique leaf page description"> 
    <title>A Cool Leaf Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
</html>

Notice between our two page components there are two meta tags with the same attribute value name="description" in our tree. You might think this could lead to duplication, but react-helmet takes care of this problem.

If someone ends up on the leaf page, react-helmet overrides the index/site-level description meta tag and renders the lower-level one, the one specifically for the leaf page.

It will also contain the viewport meta tag, since it did not have to be overwritten.

Because of react-helmet, on the leaf page, the <head> would appear as follows:

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" name="This is the unique leaf page description"> 
    <title>A Cool Leaf Page</title>
    <link rel="stylesheet" href="${ROOT}/static/index.css">
  </head>
</html>

react-helmet allows to set meta tags that will be read by search engines and social media crawlers. This makes server-side rendering and React Helmet a dynamic duo for creating apps that are SEO and social media friendly.

eg:

import { Helmet } from 'react-helmet';

<Helmet>
    <title>Turbo Todo</title>
    <meta name="description" content="test on react-helmet" />
    <meta name="theme-color" content="#ccc" />
</Helmet>

Both methods should work. But with react-helmet, the head is also treated as a component and is more react-like. Also, although it's unusual, you may bind some props or states with the meta-data to implement a dynamic head. One scenario is switching between different languages.


React Helmet also allow you to modify classes outside the scope of your render function.

For example, if you want to modify your <body> tag dynamically, you could do the following:

<Helmet>
    <body className="dynamic-class-for-body-on-this-view" />
</Helmet>