React Render Tutorial – 5 – State Immutability
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2024/01/1704775358_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: React Render Tutorial – 5 – State Immutability
All right in this video we are going to talk about rendering and state immutability we’ve already seen that when it comes to use state and use reducer react does not re-render a component when the new state is the same as the old state however our examples only involved
Working with primitive types in this video let’s understand the rendering behavior when we try to mutate objects and arrays i’m going to begin by creating a new folder in the components folder the folder name is immutable state within this folder i’m going to create a new file called object use state.js
Within the file i’m going to use the snippet rafc to create a function component next let’s import use state from react in this component we will deal with state as an object so i’m going to declare a new state variable with two properties const in its state first name is bruce
Last name is wayne we are going to use this object as the initial value for ru state hook so in the component the state variable is going to be called person the set of function is set person and the initial state is init state in the jsx i’m going to add a button
On click of which we’re going to change the first name and the last name it’s a button the inner text is basically going to be person.fname and dot l name and on click we’re going to call a function called change name now let’s define this function const change name
Is going to be equal to an arrow function and we are going to change person dot f name equal to clark and person dot l name is equal to kent and then we call the setter function set person passing in person of course we need to log the statement to verify the render
So just before the return keyword console.log object use state render let me format this save the file include it in app.js and test it out in the browser on page load you can see that we have the log statement from the initial render if i clear the console and click on the button
We are changing the properties of the person object and then calling the setter function however you can see that the component does not re-render this is again because of the object dot is algorithm that react uses when we use object as state the reference to the object must change
For the component to queue a re-render after comparing the old and the new state and this is a common mistake we tend to make as beginners directly mutating the object and expecting the component to re-render to fix this create a copy of the old state so const new person is
Equal to spread operator then the person object and then modify this new object copy so new person dot fname is equal to clark and newperson dot last name is equal to kent and then pass this into the setup function so set person new person if you now take a look at the browser
You can see that we have the initial render click on the button and the component we renders now this is also the case when dealing with array as state let’s quickly take a look at an example i’m going to create a new file called arrayusestate.js within the file
Use the snippet rafc to create a function component i’m going to import your state at the top and create a new variable called init state which is equal to an array it’s a const init state it’s an array with two strings bruce and wayne within the component i’m
Going to use the state hook and pass in in its state as the initial state so your state state variable is now going to be persons the set of function is going to be set persons and init state is the default value for the jsx i’m going to add a button
That says click and the on click handler is called handle click the button we render the list of persons so persons dot map we get access to each person and we simply render a div tag where key is equal to person and the div content or the div text
Is also person let’s now define the on click handler const handle click is equal to an arrow function and we’re going to add two more persons so persons dot push clark and then persons dot push can we finally call the setter function so set persons we pass in
Persons let’s also add the all important log statement so console.log array ustate render save the file include it in app.js and head to the browser on page load we have the log statement from the initial vendor if i clear the console click on the button we don’t see the component re-rendering
This again is due to the fact that array reference did not change for react to queue up a rerender when you push elements into the same array the array values change but the array reference itself does not change so react does not re-render the component
To fix this make a copy of the array push items and then pass the new array into the setter function so const new persons is equal to a copy of persons so spread operator and then persons and then on this copy we push the two persons so newpersons.push clark and newpersons.per kent
Finally call set persons passing in new persons if you now test this out on page load we have the log statement from the initial render clear the console click the button and we have the component re-rendering and the ui updating and this is because we made a copy of the original
Array now this rendering behavior holds good for use reducer hook as well so i’m not going to repeat the same examples with usered user however you can look at the code on my github repo for the user end user hook but this is pretty much about state immutability and render let’s quickly revisit
Our interface diagram and understand what happens we begin with the component tree we have the app component and the object use state component when we click on the button in the object use state component the state hooks setter function is called which flags the u-state component as needing an update react will go
Through the component tree and identify the flagged components it sees that object u-state component is flagged however react requires that you state or use reducer state updates must pass in or return a new reference as the new state value whether it be a new object or array reference
Or a new primitive value if it is not the case react will simply bail out from the render phase for that component this is the case we currently have since we mutate the object or the array we are not passing in a new reference so react does not even bother
With rendering the component which is the reason you don’t see a lock statement in the console and hence no ui update all right let me quickly summarize state immutability and rendering behavior mutating an object or an array as state will not cause a re-render when used with the you state
Or use reducer hug to re-render make a copy of the existing state modify as necessary and then pass the new state to the setup function or while returning from a reducer function directly mutating the state is an easy way to create bugs in your application make sure you don’t do that
All right that is about the rendering behavior in react when dealing with you state and use reducer hooks in the next video let’s talk about rendering when dealing with parent and child components thank you guys for watching don’t forget to subscribe i’ll see you guys in the next one
-
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
Please continue with next js series
As I understand, for objects it uses its reference & not its values, so till the object reference is not changed, object is same for React, so why to change the state. Object reference can only be changed by creating the new object…so if it is the case then a person with programming background will understand it better
setPerson(prev=>({…prev,fname:"bob"})) and setPersons(prev=>[…prev, "Clark", "Kent"]) is how you do it. and "initial states" are defined inside the component
In updated version of react, this will also gives you an error in the console that you cannot update state directly.
This render series have a whitish hue on screen, its kinda disturbing…
GoodJob!
You could also use this one liner:
setPersons([…persons, "Clark", "Kent"])
It just passes an array as an argument unassigned to any variable that you're making up on the fly using the previous state var (persons) and the two new values as nameless arr[2] -> "Clark" and arr[3] -> "Kent"
waise no need of comment your content always rock buddy
where is the github link ?
In the second time you can write "lex luthor"…
What is the difference between
const newPerson = {}
newPerson.fname = "Clark"
newPerson.lname = "Kent"
setPerson(newPerson)
and
const newPerson = {…person}
newPerson.fname = "Clark"
newPerson.lname = "Kent"
setPerson(newPerson)
Can you make same playslist for useEffect hook please ?
thank you very much
Thanks very much
Thanks Vishwas – This was very helpful.
Your tutorials is the best!!
Great video
why the component does not reRender ? Beacuse In Javascript objects are compared by Refrence not by value such that let a = {a:1,b:2} & let b = {a:1,b:2} console.log( a === b) output "False" , Even object a & b has same properties output is false because javascript compares object by refrence not by value . such that let a = {a:1,b:2} and let b = a , console.log(a === b ) output will be "true" because now object a and b has same memory location . same is the case in react useState hook it require different memory location rather then simply updating the properties of an object.
that was my interview question thanks vishwaz
Where were you for all these months and years..? I mean this is pure gold. I did the course of Kent Doods and Ryan Florence but the way you teach is way more awesome. Finally I understood how react works. You should make more paid courses for react , react-native or node etc. Please we'll buy it for sure. So thankful to you. Respect
VERY NICE!
Can u plz make a tutorial on next.js please. as u covering up all things related to react js it could be really beneficial to know about server side rendering . Thn x a lot.
Can you please do a series for React Native?? your tutorials are very impressive and helpful in all ways! thank you
We can achieve the same result by changing the changeName function as below. Then, what is the advantage of doing it by creating a copy of the object or array?
const changeName = () => {
setPerson({ …person, fname: 'Clark', lname: 'Kent' });
};
Sir i need a help in react state updating acc to the condition how can we do that using react hooks
Hey Vishwas…thank you so much for everything!
It really matters a lot and makes a ton of difference in our lives!
Since you are active again,and i know you don't reply often but still i am really curious on this..could you share
What do you think if react recoil?
Waiting for your reply!
React + Typescript, please make video tutorials about them. Thank bro
ty.
Your tutorials are very high quality
I've learnt alot
We love your way of teaching Vishwas ❤️