Twitter LogoFacebook Logo
useState Hook
React Hooks are functions that allow us to manipulate component lifecycle. We'll learn how to use the useState hook to update values.
By: King

Hello, in this tutorial, we'll learn how to use the useState hook, a React component lifecycle hook, to update a variable or property so the changes will be rendered.

In the Interpolation tutorial, you learned how to insert variables or properties in the component into the HTML.

And for the Events  tutorial, you learned how to add events to elements so users can interact with your app.


Now, we'll combine both of the tutorials and see how to update and render the updated values.

Why useState

In React, the rendering of DOM elements is handled by the virtual DOM (VDOM) concept. The virtual DOM is a lightweight representation of the actual DOM in memory. 

When you create React components and define their structure and behavior, you're essentially describing how the virtual DOM should look.

When there are changes in the component's state or props, React calculates the difference between the previous virtual DOM and the new one. This process is called reconciliation. 

React efficiently determines the minimal set of changes needed to update the actual DOM.

For this reason, even if you update the variable in the component, if the state of the component is not changed, it will not display the updated value.

Demo

Take a loop at this component:

function MyFirstComponent(){

    let clickedCount = 0;

    function displayMessage(event){
        clickedCount ++;
        console.log(clickedCount);
    }

    return (
        <h1 
            onClick={ displayMessage  } 
        >{clickedCount}</h1>
    );
}

There is a h1 element with a click event and a variable injected in it using interpolation.


When launch the app and attempt to click on the button, you will see no change. But when you open the Developer console (usually F12), you can see that the value of clickedCount is printed and incremented by 1 for each click.

Image from Codeible.com

As you can see, even if the value of the variable is changed, the state of the component has not changed.


To notify React that the state has changed, we need to use React component's lifecycle hooks and useState is one of them.

Using useState

Step 1:

To use useState, first import it:

import { useState } from "react";

Step 2:


Use the technique call Destructuring to extract the 1st and 2nd element from the useState function.

let [ clickedCount, setClickedCount ] = useState(0);

The useState function returns an array with exactly 2 elements. 


The 1st element is the variable or the new value for the useState.

The 2nd element is the function that we can use to update the value and notify React that a change is made. 

Now with just a little modifications to the demo code, we can update the value and state so it'll be rendered.

function MyFirstComponent(){

    let [ clickedCount, setClickedCount ] = useState(0);

    function displayMessage(event){
        setClickedCount(clickedCount++);
    }

    return (
        <h1 
            onClick={ displayMessage 
        >{ clickedCount }</h1>
    );
}

Callback Functions

So far, we used destructuring to extract the value of the state and function that handles the update. Then we used the function to set a new value.


Instead of inserting a new value, we can use a callback function.

setClickedCount(() => {


});

For this to work, at the end of the callback, it must return a value back.

setClickedCount(() => {
   return 0;
});

Now if you try to update clickedCount, the value displayed will always be 0 since the callback function is returning 0.

setClickedCount(() => {

   clickedCount++;
   return 0;

});

If you want achieve the same effect of the earlier example, we just need to put clickedCount++ in the return statement.

setClickedCount(() => {

   return clickedCount++;

});

That is all for this tutorial. Now you know how React renders stuff on the screen and how to use useState to display and update the DOM.


Sign In