Async JS and How React State works Asynchronously

Async JS and How React State works Asynchronously

What is Async Programing

Ok, So first lets understand what is Async programming. There are two types of programming one is Synchronous and another is Asynchronous.

Synchronous :

In Synchronous programming, The program statements(Instructions) waits until the previous ones are not executed. or we can say that the next line of code will not run until the previous one has not finished.

Asynchronous :

In Asynchronous programming, The program statements(Instructions) does not wait for the previous ones to finish. or we can say that the next line of code can run even if the previous one has not finished.

Why we need Async Programming

The question arises is why we need something like Async programming, so to understand that, lets take is simple example Suppose you are a chef in a restaurant, you got three orders to work on

  1. Cake
  2. Milk Shake
  3. Burger

How will you do these tasks?

One way can be, you start making the cake then bake it and after you have finished making it serve it, then start making the milk shake and so on.

Another way is you start making the cake and you put it in oven, while it bakes you can start making milk shake and serve it, and then serve the burger, and after the cake has baked, serve it.

Obviously the second method looks great, the customers does not have to wait much.

The Another way is what Async is..

How Async works in JavaScript

Javascript has somethings known as:

  • Callstack
  • WebAPI
  • Event Loop
  • Callback Queue
  • Now, here we are not going to discuss all of these things, But you can read all of them to get a better understanding.

    1_iHhUyO4DliDwa6x_cO5E3A.gif

    Image Source medium

    Let me give you some idea about few of the things

  • Callstack :
  • JavaScript engine uses a Call stack to manage execution contexts like the Global Execution Context (GEC) and Function Execution Contexts (FEC). And then push them into the stack and execute them.

    In Layman's term, This is where your code gets inserted while running and pops out after running

  • WebAPI :
  • WebApi handles the DOM, Ajax , setTimeout etc.

  • Callback Queue :
  • This is where your asynchronous code gets pushed to, and waits for the execution.

  • Event Loop :
  • The event loop keeps on running continuously and checks if the Main stack(callStack) has any frames to execute if not then it checks Callback queue, if Callback queue has codes to execute then it send them to main Stack for execution.

    Now let's see how all these things work inside Js

    So, when you run a program, the program execution context gets pushed into the Callstack, now if there is a process which will take some time to execute, Js smartly push that process into the Callback queue and keeps executing the other processes, after all the process has finished executing, The process which was pushed into the Callback queue get pushed into the CallStack and popped from the Callback queue with the help of Event Loop.

    Let's look at these codes

    The first one is Sync

    sync.PNG

    We can see that the output comes as we call the functions, like first we are calling the multiple function and then the add function, likewise we are getting the output.

    The second one is Async

    Async.PNG

    And when we have an Async code, like setTimeout, our output changes. First we get the Sum output after that we get the multiply output. Because multiple was an async function, JS ignores it and moves onto the add function and after add has finished executing, it works on the multiple function

    How React State works Asynchronously

    Now that you have understood about the Async programming and how Async works in JavaScript, lets have a look at how React State behaves Asynchronously.

    Have a look at this code

    Code.PNG

    we are just doing a simple sum, and showing its value on the screen.

    We have a button, on clicking the button we are calling the function add. Now in add function, first we are console logging the text "Adding". after that we are simply setting the state with the sum of both a and b. and after that we are console logging the value of state.

    What do you think the value of state in console output will be?

    It should be 9 right?
    Actually No ...

    Have a look at this.

    pic 1 2.PNG

    We can see the value is 9 in the HTML output, but in the console it still says 0.

    But when we again click the button we see

    pic 2 2.PNG

    When we click the button again, we can see the value being updated to 9 in the console.

    Now let's see what is actually happening

    So the initial value of State is 0, which we can also see in the h1
    Now when we click the button, we set the state to 9
    But the value we are getting in console is still 0, which is the previous state value.
    This is happening because the React State is Asynchronous, and doesn't update the value on fly.

    Hey, But we can see the value in h1 getting updated

    Yes, This is because whenever the value in React State is updated with a new value, it re-renders the component. So the newly updated value can be seen.


    But if it re-renders the component, why don't we still see the value in the console?
    This is because we are calling the console.log inside a function, and we have to again call the function to see the newly updated value in the console.

    useEffect

    The useEffect hook is used to do side Effects in react. When we use useEffect we tell React that our component needs to do something after render. The useEffect is automatically called whenever the state or props value gets changed.
    Let's look at this example.

    pic 3.PNG

    The code is same as previous ones, But we just added the console.log to useEffect hook. Now when we click the button first time, we get the updated state value in h1 and also in the console.

    so what is happening here

    ok, so we just removed the console.log from the add function, and putted into the useEffect. and we have also added the state variable in square brackets. This is to tell the useEffect that whenever the state value is updated, render whatever is inside the useEffect.
    Now when the state value is updated on button press, useEffect re-renders what ever we have putted inside it. In this case it is console.log.
    So we get updated value in console.