What is the most effective way to address the problem of my setState function incrementing by two instead of by one in my React Native application?

Why does the setPoints((prevPoint) => prevPoint + 1) in useEffect keep adding twice almost immediately?

I have tried multiple solutions, how can I adjust this so that it only increments once?

I am attempting to monitor the movement animation to determine if it reaches a specific distance indicated by the value of distanceOfScreenTopToBigCircle. However, the point state is being incremented twice almost instantly.

const theBallPosition = new Animated.ValueXY({x: 0, y: 0});

const destinationY = distanceOfScreenTopToBigCircle ? distanceOfScreenTopToBigCircle : 0;

function movingBallFunction() {

  //const destinationY = ballAtTop ? distanceOfScreenTopToBigCircle : 0;


  //This is a linear animation
  Animated.timing(theBallPosition, {
    toValue: {x: 0, y: destinationY},//This determines the distance the ball should fall
    duration: movingBallTimeDuration,//This sets the time for the ball to reach the bigCircle
    easing: Easing.linear,
    useNativeDriver: true,

  }).start();//Initiates the animation

  //Hides the instruction on starting the game once the user begins playing or when the ball is already in motion. .
  setShowHowToStartGameInstruction(false)
}

useEffect(() => {

  const animationListener = (value) => {

    if (value.y === distanceOfScreenTopToBigCircle) {

      console.log('The ball has reached its final position,', value.y)

      return setPoints((prevPoint) => prevPoint + 1);  

    }

  };

  // Attaches the listener
  const listenerId = theBallPosition.addListener(animationListener);

  // Clean up mechanism: removes the listener when the component unmounts
  return () => {
    theBallPosition.removeListener(listenerId);
  };

}, [theBallPosition, distanceOfScreenTopToBigCircle])

Answer №1

The reason for this behavior can be attributed to the latest changes implemented in React version 18. The React developers intentionally designed this feature to assist in detecting subtle bugs that may arise during the development process.

Such occurrences occur specifically when operating in Strict Mode and are limited to development environments only. Essentially, your component gets unmounted and then automatically remounted after the initial mounting phase.

To learn more about the new behaviors introduced in React v18, you can refer to the official announcement on the React Blog: https://react.dev/blog/2022/03/29/react-v18#new-strict-mode-behaviors

If you are encountering issues related to this, there is a helpful article available offering potential solutions: https://medium.com/@arm.ninoyan/fixed-react-18-useeffect-runs-twice-8480f0bd837f

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

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Create a timer that plays music when a button is pressed

My goal is to initiate a timer when a specific button is clicked. While there are many timers available that start upon page load, I have not been able to find one that begins upon clicking a button. Additionally, the timer must start at the same time as ...

When SVGs are dynamically loaded, the SVG fill with "url(#foo)" disappears

Within my AngularJS web application, I am dynamically loading various SVGs and adjusting the opacity of their layers. Some paths within these SVGs have fill pattern properties like this: <defs> <pattern id="glass-floral" patternUnits="userSpace ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Recoil: Executing a function when an atom is modified

My goal is to store a user object in an atom and cache it in localStorage every time it changes to avoid having the user sign in repeatedly if the app crashes: localStorage.setItem('user', JSON.stringify(user)) Previously, with useContext, I ach ...

Safari is unable to display the button text, while Chrome has no problem showing it

In Safari, the text of the button is not showing up properly. I am able to retrieve the text using jQuery in the console though. However, there seems to be an issue with recognizing the click event. <div class="btn-group btn-group-lg"> <button ...

Execute JavaScript script once when route changes

I'm currently working on a system where I want to ensure that my animation-based JavaScript code only runs once after the route changes. The issue I'm facing is that when switching between pages and returning to the about page, the scripts are ca ...

The frisbyjs test is not passing due to the absence of proper HTTP headers being sent by the get()

My frisbyjs test is failing because the x-access-token and x-key HTTP headers are not being sent. Am I missing something? This seems like a simple mistake. Here is the outer test that contains the failing test within afterJSON(): frisby.create('Logi ...

Eliminating Repetitions in Array of Objects by Filtering Out Objects with Matching Properties

I am currently working with an array of objects where I need to identify duplicates based on specific properties (first and last names). Below is my attempt at solving this issue: The expected output should resemble: [ {first:"John", last: "Smith", id: ...

inconsistency of nested component data

I've been troubleshooting a problem in my React project for the past 2 days. I'm fairly new to React and I'm working on creating a popup component using 'reactjs-popup'. The issue is with passing an object called items containing t ...

What is the most effective way to save and access British pound symbols?

Every so often, I face this issue where I end up resorting to a messy workaround. There must be a correct way to handle it though, as it's common to work with UK pound symbols. The dilemma is this: when the user inputs a UK pound symbol (£) into a t ...

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...

Issue encountered: Inoperable binding when employing ko.mapping with two distinct models

I've been struggling to implement a drop-down select in conjunction with a table on a page using knockout bindings. The issue arises when I try to use the mapping options in the knockout binding plugin – either the drop-down or the table behaves inc ...

Having issues with JavaScript interacting with the DOM

I'm a beginner in web programming and I'm struggling to understand why the code below isn't working as expected. It should permanently remove the content of the div element when the button is pressed, but instead, it disappears briefly and ...

Retrieve BD information using AJAX and encountering a null value in the array due to special characters

Hey, I'm using ajax to retrieve an array of data from the database: $.post ( "lib/php/load_food.php", {f:Base64.encode("primeros")}, function(data) { firsts = data; }, "json" ); However, in the 'firsts' array, strings containing accented c ...

Preventing Woocommerce from redirecting when the apply discount button is clicked during checkout using jQuery

When I manually click the "apply discount" button on the checkout page, it applies the discount and stays on the checkout page. However, if I click the "apply discount" button with jQuery on the checkout page, it applies the discount but redirects me to th ...

Using JavaScript and the PapaParse library, you can easily convert CSV data into an array

My current task involves using Papaparse to convert a csv file into a json object. The API requires the data to be structured like this: "data": [ { "id": 1, "nombre": "AGUASBLANCAS-AGB&qu ...

Automatically trigger the Submit button click with this selector

I'm having trouble automating the clicking of a 'Submit' button that only becomes clickable after a specific action is taken. In this case, the user needs to click the TOS checkbox before the button can be clicked. I've been unable to f ...

Animating toggled classes in React can be achieved by utilizing keyframe animations or

I am looking to implement a simple transition/animation using React and CSS. The concept is to have an image that, when clicked, toggles a new section below with a nice transition effect. This is my React code: const [show, setShow] = useState(false); & ...

Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list. array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", E ...