react-helmet 에 대해 기록해보려고 한다.
react-helmet 은 React 애플리케이션에서 동적으로 HTML 문서의 <head>를 관리할 수 있게 해주는 도구. 이를 통해 SEO 최적화, 소셜 미디어 공유 시 정확한 메타 정보 제공 등 다양한 이점을 누릴 수 있다.
import React from 'react';
import { Helmet } from 'react-helmet';
const ReactHelmetExample = () => (
<div>
<Helmet>
<title>React Helme tExample</title>
</Helmet>
</div>
);
import React from 'react';
import { Helmet } from 'react-helmet';
const ReactHelmetExample = () => (
<div>
<Helmet>
<meta name="description" property="og:description" content="This is a description" />
<meta name="keywords" content="Helmet, Example" />
</Helmet>
</div>
);
import React from 'react';
import { Helmet } from 'react-helmet';
const ReactHelmetExample = () => (
<div>
<Helmet>
<link
rel="canonical"
href="https://www.example.com/reactHelmetExample"
/>
<script>
{`{
"name": "React Helmet Example"
}`}
</script>
</Helmet>
</div>
);
react-helmet 라이브러리가 HTML 요소에 추가하는 속성(attribute)으로, 이 속성은 react-helmet에 의해 동적으로 관리되고 있다는 것을 나타낸다.
추적 및 식별
이 속성은 react-helmet이 HTML <head> 내에서 특정 요소를 동적으로 추가, 수정, 제거할 때 해당 요소들을 식별하고 추적하는 데 사용. 예를 들어, react-helmet이 페이지의 <title> 태그나 <meta> 태그를 추가할 때, 이를 관리하기 위해 data-react-helmet="true" 속성을 해당 태그에 추가
중복 방지
여러 번 렌더링될 때 동일한 태그가 중복되어 추가되는 것을 방지합니다. react-helmet은 data-react-helmet="true" 속성이 있는 요소만 제거하거나 업데이트하여 불필요한 중복을 피한다.
클라이언트 사이드와 서버 사이드 간의 동기화
서버 사이드 렌더링(SSR)을 사용하는 애플리케이션에서, data-react-helmet="true" 속성은 서버에서 렌더링된 <head> 내용과 클라이언트에서 동적으로 변경된 내용이 정확히 일치하도록 도와준다. 이 속성을 통해 클라이언트 렌더링 시 어떤 요소들이 react-helmet에 의해 관리되고 있는지를 쉽게 파악.
<head>
<title data-react-helmet="true">React Helmet Example Title</title>
<meta name="description" property="og:description" content="This is a description" data-react-helmet="true">
</head>
data-react-helmet="true" 속성이 있는 태그를 제거.<Helmet>을 통해 동일한 메타 태그를 생성하지 않으면, 해당 메타 태그는 삭제된 채로 남아있게 되어 결국 페이지에서 보이지 않게 된다.클라이언트에서 <Helmet> 컴포넌트를 통해 필요한 모든 메타 태그를 다시 정의. 이렇게 하면, react-helmet이 서버와 클라이언트 사이에서 일관된 메타 태그를 유지하도록 할 수 있다.
data-react-helmet="true" 속성이 있는 메타 태그는 react-helmet이 동적으로 관리. 클라이언트에서 <Helmet>을 사용하여 동일한 태그를 정의하지 않으면 react-helmet은 기존 태그를 제거하고 새로 추가하지 않기 때문에 해당 메타 태그가 노출되지 않게 된다. 이를 방지하려면 클라이언트에서도 필요한 메타 태그를 <Helmet>으로 명시적으로 설정.react-helmet은 싱글턴 패턴으로 동작하므로 서버 사이드 렌더링과 같은 환경에서는 react-helmet-async를 사용하는 것이 더 적합할 수 있습니다. 이는 동일한 API를 제공하지만 비동기 환경에서도 안전하게 동작할 수 있도록 설계되었다.