skip to Main Content

I am in the process of learning react useEffect().
In this example, "render" gets logged twice the first time I run the application.

import { useState, useEffect } from "react";

function MyComponent() {
  const [resourceType, setResourceType] = useState("posts");

  useEffect(() => {
    console.log("render");
  }, [resourceType]);

  return (
    <>
      <div>
        <button onClick={() => setResourceType("posts")}>Posts</button>
        <button onClick={() => setResourceType("users")}>Users</button>
        <button onClick={() => setResourceType("comments")}>Comments</button>
      </div>
      <h1>{resourceType}</h1>
    </>
  );
}

export default MyComponent;

It should render it once as the application is run.
Why is it printed twice in the console log.

2

Answers


  1. This is caused by React strict mode

    No need to worry, this only happens with strict mode and should not occur in production builds. This behavior is considered normal, especially in local host or development. (read below to understand why)

    Explanation

    In React Strict Mode, certain lifecycle methods, including render and effects, may be double-invoked for the purpose of detecting side-effects. This behavior is specific to development mode and is meant to help catch and log side-effect issues. It should not occur in production.

    If the double-invocation is observed only in development mode, and your application works as expected in production, it’s likely related to Strict Mode behavior.

    Solution

    Don’t worry about it when in development (strict mode), because everything is performing as expected

    Login or Signup to reply.
  2. So, when you click any of the buttons (Posts, Users, or Comments), it will cause a state change (resourceType updates), triggering a re-render of the component and resulting in the useEffect running again, logging "render" to the console.

    By passing an empty dependency array ([]), the effect will only run once after the initial render, mimicking the behavior you described.

    useEffect(() => {
      console.log("render");
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search