Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 25, 2022 04:16 am GMT

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

Hello readers, today Im 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>}

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.

Lets 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 isnt 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 dont make them too.

Keep learning and thanks for reading :)

Feel free to connect with me on -


Original Link: https://dev.to/fidalmathew/usestate-is-asynchronous-learn-how-to-use-usestate-and-useeffect-properly-1m1m

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To