DEV Community

Cover image for UseState is asynchronous: Learn how to use useState and useEffect properly
Fidal Mathew
Fidal Mathew

Posted on

5 1

UseState is asynchronous: Learn how to use useState and useEffect properly

Hello readers, today I’m gonna talk about one of the issues I faced when I was making projects using React js.

UseState is asynchronous, let me show you what I mean via a small example.

import React, { useState, useEffect } from 'react';

export default function App() {


    const [val, setVal] = useState(0);

    const addVal = () => {
        setVal(val + 1);
        console.log(val);
    }

    useEffect(() => {

        console.log("effect ", val);

    }, [val]);


    return <div>

        <div>{val}</div>

        <div><button onClick={() => { addVal() }}>ADD</button></div>
    </div>
}

Enter fullscreen mode Exit fullscreen mode

Here we are having a state variable named val initialized with 0.

We also have a button, which on click, calls a function addVal()

addVal() has the following functions -

  • Set the state of val by incrementing it.
    It is done by setVal(val+1)

  • Console.log(val);

We also have a useEffect that is triggered when state of val changes.

Let’s look at the console after clicking the button once.

console.log

1. First - The first console is of useEffect when the page first loads.

2. Second - The second console is due to the addVal function.
After, we update the state of val.

But, the value which gets printed remains the same i.e 0.

So, what happening? The value of val isn’t updated immediately, useState is asynchronous. It takes time to update so it allows rest of the program to continue and updates the value later.

3. Third - The third console log is due to the useEffect, which displays the value of val after the state is updated i.e 1.

I hope you understood the concept and remember to manage your state changes using useEffect. I have made a lot of mistakes, not knowing the concept completely. I hope you don’t make them too.

Keep learning and thanks for reading :)

Feel free to connect with me on -

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay