Search code examples
reactjscountersetstatereact-functional-component

React - setState gets updated after one click delay


So I am a beginner in React, and I was making a basic counter. I wanted the counter to display a success message once it reached 5.So I used the following code

import React,{useState,useEffect} from 'react'; import './Cards.css';

function Rules() {

const [count,setCount] = useState(0);

const [message,setMessage] = useState("");

const handleIncrement = () => {
    setCount(count+1);
    console.log(count);
    printMessage();
};

const handleDecrement = () => {
    setCount(count -1);
    printMessage();
    console.log(count);

};

const printMessage = () => {
    if (count === 5){
        setMessage("This should be displayed on 5");

    }

    else if (count === 10){
        setMessage("Thsi should be displayed on 10");
    }

    else {
        setMessage("");
    }

    

};

return(
    <div>
        <h1>Counter is at {count}</h1>
        <button onClick = {handleIncrement}>+</button>
        <button onClick  = {handleDecrement}> - </button>
        <h4>{message}</h4>
    </div>

);






    

}

export default Rules;

Now when I run the code, it gives a counter, but when I press the increment button, the success message comes on 6. When I press the decrease the counter, the success message gets displayed on 4. I checked the log and I realised that the counter displays the correct value but in the console it gets updated a moment later. Any help pleaseeee ???


Solution

  • As you are using functional component, you should add the print message logic inside useEffect hook.