Unraveling the Power of Hooks
Nitun Singh
Software Engineer at Impact Analytics | DSA Lead at GDSC(UIET, Panjab University) | LeetCode 4?
I'm thrilled to embark on my first post here and connect with all of you. As a Frontend Software Developer, I'm passionate about learning new tech stacks, problem-solving, and eager to delve deeper into various concepts. From this point forward, we'll be exploring React Hooks to gain a better understanding of how they function. Today signifies the start of our journey as we delve into the first and most commonly used hook in React, useState.
Let's kick off this conversation together — feel free to share your thoughts in the comments!
From above code in image, you see that we have a onClick listener for button that increases the value of firstValue variable. That is correct.
But what will be the output of below code ?
//What console.log(firstValue) will give output?
const handleIncreaseValue = (e) => {
setFirstValue(firstValue + 1);
console.log(firstValue);
};
If your answer is 2, then it's okay. Normally, a developer will think that it will increase the value from 1 to 2 because we are setting the value with the setter function setFirstValue. However, this is not the case with this hook.
So, what actually happens is that the setter function (setFirstValue ) triggers a re-render and stores the updated value in a queue. In the next render, the value gets updated.
The next re-render will occur only after the finishing of function execution.
So, its actual output will be 1.
You can read and follow me on medium also: https://medium.com/@nitunsingh499/unraveling-the-power-of-hooks-usestate-54781515b103
Student at UIET PANJAB UNIVERSITY || 250+ DSA questions solved|| Full stack Web Developer||
11 个月Thank you nitun sir for this??
Final Year || BE Information Technology || Software Developer || DSA enthusiast || UIET Panjab University Chandigarh
11 个月Therefore we use async, await for usestate because once state update then we go on next line
Wordpress Developer | Helping Businesses Grow and Crafting Digital Experiences| Postman API Fundamentals Expert | PU'23
11 个月Thanks Nitun for useful content??