Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

How to improve performance when rendering YouTube videos in NextJS with Sanity

3 replies
Last updated: May 21, 2023
Hi, while using NextJS with sanity I am facing performance issue as I add YouTube video in sanity text editor and then render it on website using ReactPortable Text Package.

Is there any better way to render the YouTube video so it don't affects the overall blogpage performence?
In RichComponents.tsx file I rendering video like this:


import YouTubeEmbed from "./YouTubeEmbed";
import getYouTubeID from "get-youtube-id";

export const RichTextComponents = {
  types: {
    image: ({ value }: any) => {
      return (
        <div className="relative w-full h-96 m-10 mx-auto">
          <Image
            className="object-contain"
            src={urlFor(value).url()}
            alt="Blog Post Image"
            fill
          />
        </div>
      );
    },
    youtube: ({ value }: any) => {
      const id = getYouTubeID(value.url);
      return id ? <YouTubeEmbed id={id} /> : null;
    },
  },

<YouTubeEmbed id={id} />
is a custom component that I have created

// YouTubeEmbed.tsx
import React from "react";

type YouTubeEmbedProps = {
  id: string;
};

const YouTubeEmbed: React.FC<YouTubeEmbedProps> = ({ id }) => (
  <div className="youtube-player mt-8 mb-8 justify-center flex">
    <iframe
      width="560"
      height="315"
      src={`<https://www.youtube.com/embed/${id}>`}
      title="YouTube video player"
      frameBorder="0"
      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
      allowFullScreen
    ></iframe>
  </div>
);

export default YouTubeEmbed;
May 21, 2023, 9:28 PM
Might be best to ask in the nextjs channel as this seems more like a Next.js question, not a Sanity issue.
May 21, 2023, 9:32 PM
right
May 21, 2023, 9:42 PM
https://web.dev/iframe-lazy-loading/ add loading="lazy" attribute to your iframe article below.
May 21, 2023, 10:32 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?