Deep Dive into useState: Unveiling Next-Level React Techniques ??
Nitun Singh
Frontend Developer | React.js | JavaScript | Typescript | DSA Lead at GDSC(UIET, Panjab University) | LeetCode 4?
Ready to level up your React skills? Explore a fresh perspective on useState in my latest article! Uncover new useState concepts that promise a deeper understanding. This exploration will significantly enhance your grasp of useState, enriching your React expertise along the way!
Enhance your code and tackle complex challenges by mastering the fundamentals. A clear understanding and concept clarity are the stepping stones to writing better code and solving intricate problems effectively.
Let's dive in together.
What according to you will be the output of below code:
If your answer is 3, then you are not alone. Its answer would be 1.
Let's see the logic behind this.
So, as we saw in my last article is that useState's setter function(Here it is setFirstValue ) only triggers re-render with the updated value that will be displayed in next render. Until then that will store in queue. This is because calling the set function does not update the firstValue state variable in the already running code.
Therefore, even after being called thrice, the value remains 1. Consider the value within the function as read-only until the function execution concludes. It retains the same value throughout the function's execution.
But here is a cache: We can pass another updater function to setFirstValue :
const handleIncreaseValue = (e) => {
setFirstValue(firstValue + 1); // 1 => 2
setFirstValue(firstValue + 1); // 2 => 3
setFirstValue(firstValue + 1); // 3 => 4
};
Consequently, the value will indeed increase by 3, resulting in a final output of 4.
Thank you for taking the time to read through. I hope you found this explanation insightful and valuable for your understanding.
#ReactJS #WebDevelopment #StateManagement