Monday, November 18, 2024
Google search engine
HomeLanguagesDoes React useState Hook update immediately ?

Does React useState Hook update immediately ?

React is a popular JavaScript library used for building user interfaces. It provides a simple and efficient way to create interactive and dynamic web applications. One of the core features of React is its state management system, which allows developers to keep track of and update the data in their applications. The useState hook is a fundamental part of React’s state management, but does it update immediately? Let’s dive in and explore this question.

How we can use the useState hook in React?

The useState is an API/Hook introduced in the recent versions of React. As it is a hook it let us hook into the React feature and to be precise the state feature that react provides.

In the earlier releases of React, if we want to give a state to any component then we need to convert that component into the class-based component, but with useState hook, we can give a state in our functional component. However, the useState hook can not be used in a class and should not be used in normal JavaScript functions for full-proof usage. We use the useState hook as follows and extract the state and function that update the state. The only thing that useState requires is the initial state.

How hook updates work?

React keep track of the states by queuing them in the order they are called. React queue all the changes to be made and update once the component Re-render which is not immediate. So that is how React knows which value corresponds to which state. It goes as per the queue every time the component tries to re-render.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Filename: App.js

Javascript




import React, { useState } from "react"
 
export default function App() {
 
    // State for username
    const [name, setName] = useState("jon doe");
 
    // Function to change name
    function changeName(e) {
        setName(e.target.value);
    }
 
    return (
        <div>
            <h1>Your agent name is :</h1>
            <h2>{name}</h2>
            <input value={name} onChange={changeName} ></input>
            <button>change</button>
        </div>
    )
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Explanation: As you can see to update the state we have used the method setState, which is extracted from the hook useState. So to update we have not used this.name or anything like this.setname

You might be wondering if there is no class-based component or this involved how does react know that we are referring to which state as there will be so many states in the code like below:

const [name, setName] = useState("jon");
const [surname, setSurname] = useState("doe");
const [age,setAge] = useState(23);

React do not update immediately, although it seems immediate at first glance. React keep track of the states by queuing them in the order they are called. React queue all the changes to be made and update once the component Re-render which is not immediate. This is how React knows which value corresponds to which state. It goes as per the queue every time the component tries to re-render.

Example: If our component updates the state in some order like name, surname and age, then it put those changes on the queue and do not update those state immediately as they encountered. Once the functional component ends it re-render the component and updates the state in the order in which it put them in the queue. This way React keeps the integrity of the state and lets us use the state in our functional component using the useState hook. 

setName("James");    // First state on queue
setSurname("Bond");     // Second state on queue
setAge(23);             // Third state on queue

// End of the component function

// After that re-render happens and state actually updates

References: https://reactjs.org/docs/hooks-rules.html

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments