Diesan Romero
Diesan Romero

Reputation: 1658

Why my nextjs component is rendering twice?

This is a component that render data from firebase storage and make it listed. What the function has to do is set the videos extracted from firebase storage to the useState. That way I can call videos and map into a new component, which happens to be a list of buttons. It works relatively well, the problem is that the component renders twice, the first time it doesn't save the videos in the state, and the second time it does. In other words, the component does not wait for the videos to be saved in the state, and simply renders itself, resulting in the list of buttons with the title of the videos not being displayed.

// ReactJS
import { useState, useEffect } from "react";

// NextJS
import { useRouter } from "next/router";

// Seo
import Seo from "../../../components/Seo";

// Hooks
import { withProtected } from "../../../hook/route";

// Components
import DashboardLayout from "../../../layouts/Dashboard";

// Firebase
import { getDownloadURL, getMetadata, listAll, ref } from "firebase/storage";
import { storage } from "../../../config/firebase";

// Utils
import capitalize from "../../../utils/capitalize";
import { PlayIcon } from "@heroicons/react/outline";

function Video() {
  // States
  const [videos, setVideos] = useState([]);
  const [videoActive, setVideoActive] = useState(null);

  // Routing
  const router = useRouter();
  const { id } = router.query;

  // Reference
  const reference = ref(storage, `training/${id}`);

  // Check if path is empty

  function getVideos() {
    let items = [];
    listAll(reference).then((res) => {
      res.items.forEach(async (item) => {
        getDownloadURL(ref(storage, `training/${id}/${item.name}`)).then(
          (url) => {
            items.push({
              name: item.name.replace("-", " "),
              href: item.name,
              url,
            });
          }
        );
      });
    });
    setVideos(items);
  }

  useEffect(() => {
    getVideos();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  console.log(videos);

  return (
    <>
      <Seo
        title={`${capitalize(id)} Training - Dashboard`}
        description={`${capitalize(
          id
        )} training for all Every Benefits Agents.`}
      />
      <DashboardLayout>
        <h2>{capitalize(reference.name)}</h2>
        <section>
          <video controls controlsList="nodownload">
            {videoActive && <source src={videoActive} type="video/mp4" />}
          </video>
          <ul role="list" className="divide-y divide-gray-200 my-4">
            {videos.map((video, index) => (
              <button key={index} className="py-4 flex">
                <div className="w-full ml-3 flex flex-row justify-start items-center space-x-3">
                  <PlayIcon className="w-6 h-6 text-gray-600" />
                  <p className="text-sm font-medium text-gray-900">
                    {video.name}
                  </p>
                </div>
              </button>
            ))}

            {console.log("Component rendered")}
          </ul>
        </section>
      </DashboardLayout>
    </>
  );
}

export default withProtected(Video);

This is an example of how the component is begin rendering:

enter image description here

Anyone has an idea of why this is happening?

Upvotes: 50

Views: 60357

Answers (4)

abdullah hisham
abdullah hisham

Reputation: 137

This is happening because of what has been added in the recent React updates "ReactStrictMode", to resolve it go to the next.config file and Make the code compatible with the code below

const nextConfig = {
  reactStrictMode: false,
};

export default nextConfig;

Upvotes: 4

davidtingsu
davidtingsu

Reputation: 1180

If you are trying to prevent a useEffect hook code to execute twice initially, an alternative to setting reactStrictMode to false, is to wrap the original body of code in a setTimeout function and clear the time out on component unmount.

You will see the following behavior:

  1. React component mounts
  2. React component dismounts before setTimeout callback executes, and setTimeout callback is canceled.
  3. React components mounts
  4. React component is not dismount so setTimeout callback executes.

Code:

import { useEffect } from "react";

export default function Component() {
  useEffect(() => {
    console.log('mounted');
    const timeoutId = setTimeout(() => {
      // put your original hook code here
      console.log('execute');
    }, 200);
    return () => {
      console.log("clearTimeout");
      clearTimeout(timeoutId);
    };
  }, []);

  return "Loading...";
}

If you want a react hook useEffectSafe

import { useEffect } from "react";

/**
 * Prevents double call issue in development
 * @param {*} callback
 * @param {*} deps
 */
export const useEffectSafe = (callback, deps) => {
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      callback();
    }, 200);
    return () => {
      clearTimeout(timeoutId);
    };
  }, deps);
};

Upvotes: 1

Ferruh
Ferruh

Reputation: 1376

I found the answer in this thread. https://github.com/vercel/next.js/issues/35822

In short, this issue is due to React 18 Strict Mode. You can read about what's new in the React 18 Strict Mode.

If you are not using strict mode, it should not happen. If you don't need it, you can turn off React Strict Mode in the next.config.js. file as shown below.

const nextConfig = {
  reactStrictMode: false
}

module.exports = nextConfig

Upvotes: 136

Musiur Alam Opu
Musiur Alam Opu

Reputation: 335

This is because strict mode in react is used to find out common bugs in component level and to do so, react renders twice a single component. First render as we expect and other render is for react strict mode. In development phase you will face the issue although this is not an issue. It's for better dev-experience at development phase. In production phase there will be no issue like this by default without any fault.

We can read more from : https://react.dev/reference/react/StrictMode

Moreover, if this is annoying to you you can just disable the strict mode (I personally don't prefer to disable strict mode) in next.config.js:

const nextConfig = {
  reactStrictMode: false
}

module.exports = nextConfig

Thank you!

Upvotes: 20

Related Questions