0
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: 'Enter username*',
        pass: 'Enter password*',
    })
    
    const userValidate = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
    const passValidate = /^(?=.*\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 just want that my text only change after users enter their accounts But all my useEffect always execute immediately after initial render without any interactions though I have put dependencies for them

  • 1
    That's how effects work - they always run after a render. Maybe initialise the state with `null` and then check in the effect that `username` etc is _not_ null to determine whether you should be setting the error state. – Andy Aug 18 '23 at 11:24
  • 1
    You can take a look at making your own custom effect hook, as shown here for example: [Make React useEffect hook not run on initial render](https://stackoverflow.com/a/57941438). Also worth reading this: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect), as you might find that you don't need an effect and might be causing more rerenders than what's needed. – Nick Parsons Aug 18 '23 at 11:53

1 Answers1

0

useEffect runs after the first render, and for every change in your dependencies array.

You can prevent the useEffect from running in the first render by having a check like:

const [password, setPassword] = useState('')

useEffect(() => {
    if (password) {
        setErrorPassword(passValidate.test(password))
    }
}, [password])
Robin Thomas
  • 1,317
  • 8
  • 15