Why my nextjs component is rendering twice?
Asked Answered
M

4

44

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?

Microscopy answered 12/4, 2022 at 18:54 Comment(6)
Are you ensure that rerender is called only in Video? Maybe parent component force rerender.Alburg
@Alburg There is a parent component which is the dashboard layout. That one is also rendered but together with the child component. I notice that because they both render twice. The reason why I put the logout function in the console log is to check that precisely. Since the logout function is only rendered in the layout.Microscopy
useEffect calls getVideos that sets state - state changes cause rerenders.Maternity
@SeanW Something like that I suspect. This happens when I call getDownloadUrl inside listAll. I assume that each time each is called the state is re-rendered. The problem is that I need information from both. listAll to list each of the videos and display them in the list, and getDownloadUrl to access the firebase url and then be able to render the video in the editor. There is any way to solve it?Microscopy
I think that setVideos(items): is called twice because you are not awaiting for the async API calls. What happens if you move the setVideos(items); immediately after the res.items.forEach? Could that help? Or you could try to await all the async API calls and then use setVideos(items):.Asocial
You'll always re-render the component because you're updating state inside useEffect. If you want to avoid that, fetch the videos data on the server-side instead.Badmouth
B
120

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
Butanone answered 10/5, 2022 at 12:58 Comment(2)
There was reactStrictMode but not version 18. Should happens the same?Microscopy
It should be noted that this only affects development mode as per the above link: "This only applies to development mode, production behavior is unchanged."Directional
B
15

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!

Bookkeeper answered 15/5, 2023 at 10:3 Comment(2)
Hey, any idea how we can handle api calls for this? because twice render, it ends up calling api twice? any suggestions?Lyautey
@BahrozeAli Would you like to add a content how you fetch or call the API?Bookkeeper
D
1

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);
};
Darkness answered 6/1 at 6:33 Comment(1)
In practice, you should avoid using useEffectSafe, the double rendering is supposed to help you catch issues such as calling functions that are no idempotent.Darkness
R
1

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;
Romanism answered 21/2 at 19:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.