What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue...

This code triggers twice in a row, causing the useEffect function to run twice per second.

'use client'
import {useState, useEffect, useRef} from 'react'

export default function Home() {

  const [timer, setTimer] = useState(null)
  let intervalId = useRef(null)
  const start=()=>{
    setTimer(900)
    intervalId.current = setInterval(()=>{
      setTimer((timer)=>timer-1)
    }, 1000) 
  }

  useEffect(()=>{
    if (timer < 1 && timer != null) {
      setTimer(null)
      clearInterval(intervalId.current);
      console.log("proccccccccccccc")
    }
  }, [timer])

  useEffect(()=>{
    start()
  }, [])

  return (
    <main className="">
       {timer}
    </main>
  )
}

The function executes once per second when removing the condition && timer != null in the useEffect.

'use client'
import {useState, useEffect, useRef} from 'react'

export default function Home() {

  const [timer, setTimer] = useState(null)
  let intervalId = useRef(null)
  const start=()=>{
    setTimer(900)
    intervalId.current = setInterval(()=>{
      setTimer((timer)=>timer-1)
    }, 1000) 
  }

  useEffect(()=>{
    if (timer < 1) {
      setTimer(null)
      clearInterval(intervalId.current);
      console.log("proccccccccccccc")
    }
  }, [timer])

  useEffect(()=>{
    start()
  }, [])

  return (
    <main className="">
       {timer}
    </main>
  )
}

Despite multiple readings, the reason behind this behavior is still unclear...

Answer №1

If you're encountering this issue, it could be due to running your app in strict mode. To troubleshoot, check if the React.StrictMode element is included in index.js. This element can cause everything to render twice in order to identify any issues. When building the app for production using npm build, it should work as expected. However, if desired, you can remove the strict mode element. Just keep in mind that removing it may not catch all problems, but many developers choose to do so to simplify things.

Answer №2

If you are currently running the server in development mode, it's important to note that this is intended behavior and should not affect production builds. If necessary, you have the option to disable strict mode by removing the <React.StrictMode> tags from your App.js file.

Strict mode serves the purpose of helping you identify bugs within your application. It works to re-run effects and renders in order to pinpoint any issues stemming from impure rendering or faulty effect cleanup. I highly suggest keeping it enabled unless you have a specific reason to disable it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving discount codes from Shopify

I'm currently working on developing a Shopify checkout extension that aims to retrieve available discount codes. However, I've encountered an error stating "Cannot read properties of undefined (reading 'codeDiscountNodes')." My approach ...

What is the best way to call another "put" action method within the same controller file?

My project revolves around the interaction of two models - User and Request. A User can create a food delivery Request, attaching tokens as rewards. Another User can then help deliver the request and claim the tokens. Within the same controller.js file, I ...

Tips for retrieving a parameter from the oncomplete attribute of an a4j:jsFunction tag

Is it possible to access a parameter for an <a4j:jsFunction> in the oncomplete="" attribute without using the action="" attribute and assingTo="" of <a4j:param>? <a4j:jsFunction name="refreshTableFilter" render="table,scroller" execute="@fo ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Guide on Generating Dynamic JSON to Set and Retrieve Values for Forms and Displaying the Bound Values

I'm a beginner in Ionic 3 and I'm having trouble creating a page that redirects to another page without validation. I want to display the data on the new page, but it's not working. Please help! I also want to create a dynamic JSON object a ...

JavaScript code to read a .txt file

Is it possible to use JavaScript to read a text file directly with the file path provided in the code, rather than selecting the file from an open file window? ...

Is it possible to save the project by generating incremental JSON diffs?

In the process of developing a web-based paint program, I have implemented a system where the user's artwork state is saved as a json object. Each time an addition is made to the client's undo stack (which consists of json objects describing the ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

Utilizing React to invoke the filter method on Object.keys

A specific React component receives a state property that consists of nested objects: { things: { 1: { name: 'fridge', attributes: [] }, 2: { name: 'ashtray', ...

Adding nested JSON data to MySQL using NodeJS

My current challenge involves using Node.js to INSERT JSON data into a MySQL database. Everything runs smoothly until I encounter nested values within the JSON structure. Here is an example snippet of my JSON data: var result2 = [{ "id": 89304, "employe ...

Modify Chartjs label color onClick while retaining hover functionality

Currently, I have implemented vue-chart-js along with the labels plugin for a donut chart. Everything is working well so far - when I click on a section of the donut chart, the background color changes as expected. However, I now want to also change the fo ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

The form creation and modification rendering feature in API Platform Admin isn't functioning properly

I'm facing an issue in my admin panel where the API functions correctly for posting and getting data. However, when I try to create or update objects using the admin panel, I encounter a blank form. You can view the screen here. Additionally, there i ...

ReactJS Issue: Failure of Validation on Auto-Populated Form Field

I encountered an issue with the validation setup in my form. The validation checks the input values for "required", "max length", and "min length". Oddly, the validation only works for fields where the user manually types into the input field. I made some ...

Issue encountered with AJAX multiple image uploader

I'm attempting to create an PHP and JavaScript (jQuery using $.ajax) image uploader. HTML: <form method="post" action="php/inc.upload.php" id="upload-form" enctype="multipart/form-data"> <input type="file" id="file-input" name="file[]" a ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

Directing users to a specific section on another webpage can be accomplished using HTML, JavaScript, or

<nav> <div class='container-fluid'> <h1 class='logo'>Logo</h1> <ul class='list-unstyled naving'> <li><a href='index.html'>Home</a></li> ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Learn how to toggle between two different image sources with a single click event in JavaScript

If the button is clicked, I want to change the image source to one thing. If it's clicked again, it should change back to what it was before. It's almost like a toggle effect controlled by the button. I've attempted some code that didn&apos ...