React Hooks Tutorial – 3 – useState with previous state
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703603525_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: React Hooks Tutorial – 3 – useState with previous state
In the previous video we had a look at a basic example on how to implement the u.s. state hook in this video let’s take a look at another example this time how to set state based on the previous state value once again we are going to be implementing a counter but this counter
Will have buttons to increment decrement and reset the count value I’m going to begin by creating a new file in the components folder hook counter to dot j/s within the file I’m going to use the react snippet RFC e to create a functional component next we use the you
State hook to create a state variable and the corresponding setter function the count comma set count is equal to you state with a default value of initial count now we can add the GSX count is going to be count itself and then we add the three buttons to reset
Increment and decrement the count value so for the reset button on click is going to be an arrow function call set count passing an initial count as the argument this will set the count value back to zero next we have the increment button on click call set count and the
Argument is going to be count plus 1 similarly for decrement on click is going to be set count count minus 1 we can now include the component and app component hook counter to dot J s if you save the files and take a look at the
Browser we must have the new counter I click on increment and the count increases click on decrement the count decreases and clicking on reset will set it back to zero now you might be wondering what is so special about this example how does it differ from what we
Have seen in the previous video well here’s the thing the current implementation and the way we incremented count value in the previous video both are unsafe although it looks like it is working it is not the right way to change the count value let me show you why with a very
Unlikely piece of code you would implement I’m going to add another button that increments the count by a value of 5 text is going to be increment 5 then on click let’s call a function called increment 5 now let’s define this increment 5 is an arrow function and
Within the body for that I is equal to 0 I less than 5 I plus plus and we call set count incrementing it by 1 every time so rather than incrementing it by a value of five and simply looping it five times and incrementing by one every time
If we go back to the browser and test this out click on increment five you can see that the count is still incremented by only one the set count method is reading a stale value of the count state variable to overcome this we need to use the
Second form of the set count function basically instead of passing in a value of the new state variable we pass in a function that has access to the old state value so set count is going to accept a function that has access to the old count so previous count is going to
Be the argument and the function body previous count plus one so we pass in a function that has access to the old value and increment that by one now if we go back to the browser and test it out increment five you can see that the value increases by five so anytime you
Need to update state value based on the previous state value always go with the safer option of passing in a function that will set the new state value let me make the changes for increment and decrement buttons as well to copy this paste it here and here and change plus
To minus if you now take a look at the browser you should see the counter still working perfectly fine all right that is the second example when you have to update state based on the previous state value pass in a function to the state setter let me also quickly show you the class
Component equivalent so if I go back to components and class counter to yes you can see that we have the increment count function we call set state passing in a function the function has access to the previous state which we use to calculate the new state again if
You’re new to class components don’t worry about this now we are not quite done with all the details of you state hook let’s take a look at another example in the next video thank you guys for watching feel free to subscribe and make sure to click on the bell icon for notifications
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Hi, How can we stop decrement numbers from going to minus – value. ?
React batch the frequent state changes and set only necessary states at the end to provide performance.
But why then setState( prev=>prev+1) works?
Actually what happens is
Let us take an example:
Let state = 0
We set state two times in two ways
1)
setState(count+5)
setState(count+5)
//result : state =5
2) setState((prev) =>prev+5)
setState((prev) =>prev+5)
//result : state =10
In the first case react would check whether there is any changes in these two states or not
Like this
count+5 ===count +5 //true
This equality causes react to do only one set state avoiding unnecessary state changes ( according to react Prospective it is unnecessary😅(
in 2nd case :
React again does equality comparison:
(prev) =>prev+5 === (prev) =>prev+5
//false (checking function equality, not returned value)
Which turns out to be " false"
And consider these two setStates to be different which results changing the state two times.
So it's becuase of referential equality why react does not change state in the first case
Note : in JS
[1, 2,3] ===[1, 2,3] //false
{ } ==={} //false
() => {} ====() =>{} //false
i write this code and it's works properly
any thing wrong please tell what i made mistake
import React, { useState } from 'react'
export default function Counter() {
const [count,setcount]=useState(0)
const increase=()=>{
setcount(count+1)
}
const Decrease=()=>{
setcount(count-1)
}
const setfive=()=>{
setcount(count+5)
}
return (
<div>
<h1>count:{count}</h1>
<button onClick={increase}>Increase</button>
<button onClick={Decrease}>Decrease</button>
<button onClick={setfive}>SetFive</button>
</div>
)
}
I love the way you teach, and I love the time and effort you put into these videos. Saying that, there's a bug at 05:25 that it seems everyone's overlooked. You hit the Increment 5 button but the counter decreases, only on the next click of a button the number increments by 5
why don't we use setCount(count + 5) for incrementing value to 5 every time ?
import React, {useState} from 'react';
function App() {
const [initialValue, setInitialValue] = useState(0);
const [count, setCount] = useState(0);
const myFunc = () => {
setInitialValue(initialValue+ 1)
setInitialValue(initialValue + 1);
};
const myCountFunc = () => {
setCount(prevState => prevState + 1)
setCount(prevState => prevState + 1)
};
return (
<div>
<button onClick={myFunc}>state value: {initialValue}</button>
<button onClick={myCountFunc}>state value: {count}</button>
</div>
);
}
export default App;
Just observe the output of the function by clicking one by one on both the buttons
10:45PM Episode 03 down!!!
why not directly use setCount(count+5) ???
What are those extensions name when typing it, it will automatically create a function at 3:15?
S E N S A C I O N A L ! TUDO Muito bem explicado ! ! Parabéns pelos vídeos ! ! !
Thanks
const IncermentFive=()=>{
for(let i=1;i<=5;i++)
{
setCount(count+i);
}
}
hi vishwash, i need your attention , this is actually works same as you describe ….is this right way ??
Done thanks
When updating state based on previous value, always use the setState(…) function that takes a lambda that takes the previous state value. Don’t use setState(oldStateVar + 1) and especially don’t call it in a loop. That’s why just always use the version that takes function that takes previous state
<Button
title="+"
onPress={() => {
setCount((prevCount) => {
return prevCount + 5;
});
}}
></Button>
Why pevCount is incrementing by 5, will it not break after just after one updation and state will re-render the component and the answer would be count : 1 ?
Confusing at 4:25: “going to accept a function that has access to the old count” … ‘prevCount’ is introduced with no discussion of where it came from. Turns out the React Hooks reference for useState is just as vague (Google it, YouTube doesn’t allow URLs).
The complete discussion:
“If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here’s an example of a counter component that uses both forms of setState.”
The example shows ‘prevCount’, the only place in the reference where it’s mentioned. I gather this is because 'prevState' is a function from JavaScript (predating React), so 'everyone' should know about it 🙂
{2022-10-14}
for incrementFive method we have assigned datatype as const but for in class for increment count we didnt add any datatype. if we add datatype hen we r getting error. why so? can anyone eplain??????
I didn't get it PrevCount
In increementFive function, why haven't the tutor used variable i in setCount function. As he has used i in the loop, so setCount( count + i ) should be used. It will work fine and we need not require prevState.
I think you shoud have explained why this unsafe method of updating state is `unsafe`. Though i am not a react expert and other folks here can correct me, the reason why multiple calls to setState does not work as expected is because of the fact that react is seeing the value of `count` which was available at the component load, so even though the calls to setState itself are async, all of the calls are still updating the same value by 1. By using the second variant of setState by passing an arrow fxn u are registering a callable which react would call and it knows that i need to pass the most recent state value as the first arg to this callable.