score:1

Accepted answer

The issue lies in the fact that setting state is an asynchronous process.

In your updateScore method, you are setting the newly computed strength to the state. But remember that setting a state is asynchronous activity. So you would not get the updated state to compute your strength message, since it hasn't been updated yet.

For this to work properly, instead of using the strength from the state to compute your message, you can use the return value of passwordStrength method.

const updateScore = (props) => {
    const newStrength = passwordStrength(props);
    setStrength(newStrength);
    setpwInput(props);

    if(newStrength ===0){
        setHiddenStatus(true);
        setStrengthMessage("We need a strong password");
    }
    if(newStrength > 0 && newStrength <= 2){
        //weak sauce
        setStrengthMessage("Weak sauce :(");
    }
    if(newStrength ===3){
        //better
        setStrengthMessage("Better...");
    }
    if(newStrength ===4){
        //great
        setStrengthMessage("Great");
    }
    if(newStrength >=5){
        //outstanding
        setStrengthMessage("Outstanding!");
    }
}

score:2

before setting strength try storing the password strength value in a variable and then use it instead of the hook inside function for setting strength message

const updateScore = (props) => {
    let temp = passwordStrength(props)
    setStrength(temp)
    setpwInput(props)

    if(temp ===0){
        setHiddenStatus(true)
        setStrengthMessage("We need a strong password")
    }
    if(temp > 0 && temp <= 2){
        //weak sauce
        setStrengthMessage("Weak sauce :(")
    }
    if(temp ===3){
        //better
        setStrengthMessage("Better...")
    }
    if(temp ===4){
        //great
        setStrengthMessage("Great")
    }
    if(temp >=5){
        //outstanding
        setStrengthMessage("Outstanding!")
    }
}

Related Query

More Query from same tag