Does React useState Hook update immediately ?
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.
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:
Project Structure: It will look like the following.
Step to Run Application: Run the application using the following command from the root directory of the project:
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