Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false)
    const [username, setUsername] = React.useState('')
    const [password, setPassword] = React.useState('')
    const [errorUsername, setErrorUsername] = React.useState(true)
    const [errorPassword, setErrorPassword] = React.useState(true)
    const [text, setText] = React.useState({
        user: 'Input your username*',
        pass: 'Enter your password*',
    })
    
    const userValid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
    const passValid = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{0,}$/

    React.useEffect(
        () => setText({
            user: errorUsername ? 'Username*' : 'Invalid username',
            pass: errorPassword ? 'Password*' : 'Invalid password',
        }),
        [errorPassword, errorUsername]
    )

    React.useEffect(
        () => {
            setErrorPassword(passValidate.test(password))
        },
        [password]
    )

    React.useEffect(
        () => setErrorUsername(userValidate.test(username)),
        [username]
    )

I am encountering an issue where the content of my text variable changes as soon as the page loads, even before any user input. I have set up dependencies for my useEffect hooks to trigger only after users enter their account details, but they are executing immediately upon initial render. Any help in resolving this would be greatly appreciated.

Answer №1

After the initial render, useEffect will execute, and it will also run for every alteration in the array of dependencies.

To avoid the execution of useEffect during the first render, you can include a conditional check like this:

const [username, setUsername] = useState('')

useEffect(() => {
    if (username) {
        setErrorUsername(validateUser(username))
    }
}, [username])

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 am looking to present a nested array within an array in a tabular format

This is the structure of my database: [{ "firstName": "Shaun", "salary": [ { "id":1, "rate": 250, }, { "id":2, "rate": 290, } ] },{ "firstName": "Julian", "salary": [ { "id":1, "rate": 750, ...

Unlocking Column Data Tooltips in Angular Datatables: A Step-by-Step Guide

I have a single datatable and was wondering how to implement tooltips for when hovering over table cells. I tried the following code snippet, which successfully populated the tooltips. However, I am interested in achieving the same functionality using Angu ...

In the context of Express, how are "static" and "non-static" defined?

The Express documentation explains that the express.static() middleware is used to serve static files like images, CSS, and JavaScript. However, when serving a front-end React app using express.static("some_build_dir"), which includes JS files ...

What is the best way to transmit a Blob object to the server without it arriving empty?

I'm currently facing an issue where I am attempting to send a Blob object containing video data to my server for upload to my S3 storage. However, the Blob is arriving as an empty object on the server side. const blob = new Blob(videoChunks, { t ...

What is the reason that .bin/www is recognized as a JavaScript file even though it does not have the .js extension when utilizing express-generator

Can you explain why .bin/www is recognized as a JavaScript file by express-generator even without the .js extension? Whenever I create a bin/ folder with a www file inside, it's automatically identified as a JavaScript file despite the missing .js ex ...

By utilizing a combination of JavaScript and jQuery, we can dynamically fill interconnected select boxes with data from an

After finding solutions to this particular query, I successfully managed to populate a select box based on the selection made in another select box. (You can see my answer here) This was achieved by retrieving data from an array structure that was generate ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

Removing data from firestore/storage does not follow the expected pathway

I have created an image gallery for users using Firebase Storage and React, allowing them to upload and delete images. However, I am facing an issue where the deletion process is taking longer than expected. Expected flow: User clicks on the trashcan ico ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Display the output of JSON.stringify in a neatly formatted table

After sending my table data to the database using ajax, I am now trying to retrieve it by clicking on the open button. $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...

Regular expression: Identify all instances of double quotes within a given string and insert a comma

Is there a way to transform a string similar to the following: ' query: "help me" distance: "25" count: "50" ' Into either a JavaScript object or a JSON string that resembles this: '{ query: "help me", distance: "25", count: "50" }' ...

Set $scope.model childs to an empty string or a null value

While working on a form, I am using a $http request to send the information through Angular in the following manner: $http({ method:"POST", url: "controllers/servicerequest.php", data: { servicerequest: $scope. ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Utilizing the ref received from the Composition API within the Options API

My current approach involves utilizing a setup() method to bring in an external component that exclusively supports the Options API. Once I have imported this component, I need to set it up using the Options API data. The challenge I face is accessing the ...

Exploring the creation of an Angular service that utilizes HttpClient for making GET requests, with a focus on the different

I've been diving into Angular lately and I'm facing some challenges with handling get requests. If you're interested, you can check out my code on Angular Stackblitz import { HttpClient} from '@angular/common/http'; import { Inject ...

Setting up a Lerna monorepo with TypeScript: A Comprehensive Guide

I have a central repository with the following details in config.json: "main": "dist/cjs/index.js", "module": "dist/esm/index.js", "es2015": "dist/es2015/index.js", "types": "dist/es2015/index.d.ts", "typings": "dist/es2015/index.d.ts", The repository co ...

Time when the client request was initiated

When an event occurs in the client browser, it triggers a log request to the server. My goal is to obtain the most accurate timestamp for the event. However, we've encountered issues with relying on Javascript as some browsers provide inaccurate times ...

Error encountered: npm process ended unexpectedly with error code ELIFECYCLE and errno 2

Whenever I attempt to run - npm run dev in my command prompt, I encounter the following error: Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. Hash: af4cfdb00272137cb4d3 Version: web ...