React uses Fiber architecture now. When you update state it creates a singly linked list of effects. This effect list helps in asynchronously run the reconciliation algorithm and create the work in progress tree of Fiber with new values. Then it synchronously performs the commit on actual DOM. ( the algo uses iterative singly linked list traversal as opposed to recursive approach in earlier version) Really understanding react internally is difficult but that’s when people will understand what is going under the hood .
0:48 "React mutates the state variable" - this is exactly why everyone got confused and commented in the previous video If we consider inst.state = bla here, state is not mutated, component's instance (inst) is mutated Your understanding and explanation is correct but the statement should be something like "React mutates the component's instance with the new state and props..."
You're right, that part made sense in my head but I did not deliver that properly in last video. I understand the confusion too. IMO, it wouldn't be wrong to say that you are also mutating the 'state' property on inst object. That's what I meant when I said state is mutated. But I get your point.
I understand what you were trying to bring up in the previous video now. The state in the class-based component is accessed by looking up this.state, which is mutated on component update. That's why functions that run another function with closure like setInterval can still access the updated value at a later time. However, there are ways to get the setInterval in a functional component in your example working. I think this video could be better by including the solution in the video as well, and explain why it works. Otherwise, people who don't know might think that this is the limitation of functional components, and would only use class-based components for timer-like requirements.
to fix the functional component, you have to pass a function in setCount, in which react gives you the up-to-date state. i.e. setCount(prevCount => prevCount + 1)
@@arpitdalal_dev Yup. Alternatively, add `count` to the `useEffect` dependency array. Don't forget to run `clearInterval` in the `useEffect` clean up function
For those who are wondering, how to get the timer to work in functional component , you can get the current state as an argument in setCounter. setCounter(count=>count+1); Incidentally this has been my interview question for quiet some time as well. For bonus , I usually ask them to stop the counter with clear interval.
can you please explain why changing the code to this will get the required functionality. i mean what is the difference between putting count as an argument and directly using it.
8:15 you are re-assigning inst.state, not mutating it. "mutation" would involve changing the existing inst.state value. however, you are mutating inst. 😀
I think if you’re fundamentals are strong and understands classes and objects , you would be curious and would want to peek under the hood to see how “React” does it’s thing. It’s just something that you’d ask yourself naturally.
@@aswincg5895 I didn't say it's done by many, but for those that are experienced , I think this sort of thinking is eventually inevitable. Don't take it personally, it's not a n attack, I'm also not good at it. But I don't think my view is entirely wrong here. That's all from my side. Thank you. Please don't expect further response from me.
It is reassignment not mutation, the new state is a different ref completely. If something is mutated (ex: a) then if you do oldA===newA should return true, in this case its not the same because its not mutated its reassigned, and react decides to rerenders only if it gets a new ref, so if you have this.state={a:1} and u have onclick that changes a to 1 (you are not changing it since it was 1 already) Class based comp would still rerender because of new ref for the whole state(reassigned, not mutated). Whereas functional with hooks won’t rerender, because the value didn’t change. I’m glad u made a vid for more views and content
@@shreyashc So he is saying, that the component object is being changed, where as functions always get replaced with new ones. Duhh that's the point of functional programming vs oop. I understood completely what he wanted to say, I was just trying to tell him to be more correct and specific in his words especially if the goal is for new people to understand.
In this case below example why the counter is working properly ? In case of setinterval example the counter was reinitializing to 0 again and again, but in below case why this is not happening? I am just curious to know. Can you exaplain this? function App() { const [counter, setCounter] = useState(0); const incrementCounter = () => { setCounter(counter + 3); }; return (
Is SSG in next.js with firestore getDocs not possible. I am trying it. I get result same way with fetch but getting const q = query(collectionRef, where("brand", "==", "PODS")); > 40 | const podData = await getDocs(q); this second line gives me error
In my understanding of javascript, inst. state = nextState doesn't prevent object mutation like Object. assign({},inst.state, nextState) would do. But by initializing the state Object in the Class constructor, our state Object is defined and predictable, so we are just going to update the state without adding a new property to the state object (mutate it). it would be great if someone could correct my way of thinking about it
Inside the setInterval method just this one liner is required- setCount (prevCount => prevCount + 1) This allows the setState method in a functional component to access the current state and then update it... In the background this is because the set state method in a functional component doesn't mutate the state property of its inst object therefore we have to pass in the previous/current state value manually each time
@@zathkal4004 although this would work for simple state but for more complex state you can use `useReducer` because you have both state and actions/props at the hand to do your stuff, simply using `useState` won't work. Additionally you can also write declarative way to implement `setInterval` for hooks. Give "Making setInterval Declarative with React Hooks" by dan abramov a read, you will understand everything.
@@harshkc99 it was code for a beginner as mentioned by the initial commenter mate.... Moreover, obviously useReducer is the way to go while larger states involving the contextApi and so forth but like I said my answer was to a beginner. Thanks anyway for your comment
So how do you mirror the behaviour of the class component state updation in the functional component useEffect hook for the particular scenario you just mentioned in the setInterval example ?? What's the solution? Can it not be done at all??
As always...Mehul Bhai thank you so much !!! Now I have one doubt due to this "Is this the reason why the functional component is not set the state just like class component does ? I mean we have to provide the previous state to setState for functional component because it returns the last state every time it re-renders".
Mehul sir, The state is NOT mutated. It's "Reassigned " . inst.state = {a:'' random variable'} will have a new reference is memory, thats why it will be rerendered. I wish you would have compared the equality of both state while debugging, like you did for later. I am very sure, it would have returned false.
Nope, reassignment is NOT mutation. State never gets mutated in React. The general idea you're trying to convey is right - the component instance gets mutated, but all the people arguing that the state is not mutated were right. You were the one in the wrong, because what you said was a false statement.
I really enjoyed this in depth analysis of React. Very informative. Just a quick question, Here inst.state = newState, aren’t we mutating inst itself and not the state. Infact we are reassigning state by inst.state = newState and Hence mutating that particular instance but not the state property of that instance.
I understand the confusion too. IMO, it wouldn't be wrong to say that you are *also* mutating the 'state' property on *inst* object. That's what I meant when I said state is mutated. But I get your point.
@@codedamn I think I disagree :) By reassigning you're pointing to a new memory location which holds a different value. Mutation is when pointing to the same memory location but updating that value it holds, right? But anyway, very informative vids. Encouraged me to finally look into React's source code soonish. Maybe it would've also been cool to mention, that count is a closure variable in the function based component (in the setInterval's anonymous fn). I think if you would put a console.log('render') in the function body, the component is indeed rerendered, but the state is always set to the same value in memory. Yeah but maybe that wouldn't haven been too relevant for the point you wanted to make.
how do you even have that much understanding? I want this level of knowledge but can it only be achieved by digging deep myself or I can get that level of information somewhere
8:16 , true that inst is being mutated when its state property is triggered which was initially triggered by the state = value (value that state holds) getting reassigned Using an objective approach I feel that the React team wanted to keep their documentation free of tech jargon in order to be beginner friendly as well I suppose, by simply meaning the following - That a setState call would mutate the inst property eventually through its state property when the state's value gets reassigned..... Just different wordings by the React team with the same goal in mind I guess... Awesome job sir !
there is a difference between mutating vs reassigning a variable, they are not the same, in the source code they are clearly reassigning and not mutating inst
What was the point of these both videos? React manage state for class and functional component different way. but it does not effect our devlopment or the core idea of using react. The setimeout example is also wrong. you need to use prevState if you are updating a state with its own value. useEffect(() => { setTimeout(() => setTime((prevTime) => prevTime + 1), 1000); }); for class component syntax would be different but idea remains same.
so just wanna know if inst.state = nextState and if nextState = {...inst.state, nextState} will that be mutation? How does nextState is calculated/computed?
I don't know anything about React (just learning and was wondering whether should do functional plus hooks or classes or both) and just from how he's misrepresenting what people say is enough proof for me that he has no idea what he's talking about. Class in JS is a function (he agrees) hence React Class is also a function (no because it's written different then a function). Fuck me... Also I like how people are pointing out something he said wrong, but no no guys, I didn't mean it like that. I oversimplified. Yeah, nice moving of the goalpost.
Mahul is a genius, but I think as a teacher he fails to convey his thoughts properly to students, I watched his lots of videos buy I always get confused, Maxmullian from acadamind is great at teaching, even normal student understand his stuff...
Just something to add into your video. const [counter, setCounter] = useState(1); counter = 2; raises Error is because you try to assign to a constant variable. I can't tell it's just a static checking without further investigation. Since array in fact is an object in JavaScript; const statehook = useState(1); statehook[0] = 2; this will pass the checking but it will definitely cause some runtime problem. It's just the annoying traditional JavaScript object problem with `const` keywork.
That is exactly why chapters exist in the video. I’m sorry sir but if your attention span is less than goldfish there’s no way to explain react internals in that small duration
You'd need to watch the last video to understand this one: ua-cam.com/video/JxzzpDHYYXk/v-deo.html
"You read the docs, I read the source code." OP Line by Mehul
Pretty bold statement for a dev that does not know what mutation means
React uses Fiber architecture now. When you update state it creates a singly linked list of effects. This effect list helps in asynchronously run the reconciliation algorithm and create the work in progress tree of Fiber with new values. Then it synchronously performs the commit on actual DOM. ( the algo uses iterative singly linked list traversal as opposed to recursive approach in earlier version)
Really understanding react internally is difficult but that’s when people will understand what is going under the hood .
0:48 "React mutates the state variable" - this is exactly why everyone got confused and commented in the previous video
If we consider inst.state = bla
here, state is not mutated, component's instance (inst) is mutated
Your understanding and explanation is correct but the statement should be something like "React mutates the component's instance with the new state and props..."
You're right, that part made sense in my head but I did not deliver that properly in last video. I understand the confusion too. IMO, it wouldn't be wrong to say that you are also mutating the 'state' property on inst object. That's what I meant when I said state is mutated. But I get your point.
I understand what you were trying to bring up in the previous video now. The state in the class-based component is accessed by looking up this.state, which is mutated on component update. That's why functions that run another function with closure like setInterval can still access the updated value at a later time.
However, there are ways to get the setInterval in a functional component in your example working. I think this video could be better by including the solution in the video as well, and explain why it works.
Otherwise, people who don't know might think that this is the limitation of functional components, and would only use class-based components for timer-like requirements.
to fix the functional component, you have to pass a function in setCount, in which react gives you the up-to-date state. i.e. setCount(prevCount => prevCount + 1)
@@arpitdalal_dev Yup. Alternatively, add `count` to the `useEffect` dependency array. Don't forget to run `clearInterval` in the `useEffect` clean up function
For those who are wondering, how to get the timer to work in functional component , you can get the current state as an argument in setCounter.
setCounter(count=>count+1);
Incidentally this has been my interview question for quiet some time as well.
For bonus , I usually ask them to stop the counter with clear interval.
can you clarify
for clear interval, we can return cleanup function in useEffect() right?
can you please explain why changing the code to this will get the required functionality. i mean what is the difference between putting count as an argument and directly using it.
@@reddisharan9766 the set state function of useState hook would always send the current state as argument, which is exactly what we want here
Ot you can also pass the count in the dependency array and clear the timer ... that would not be better solution though
8:15 you are re-assigning inst.state, not mutating it. "mutation" would involve changing the existing inst.state value. however, you are mutating inst. 😀
right, this is not mutation.
I guess that's why all the devs he interviewed failed :P
Dude how do you learn such advanced concepts. Do you recomend reading the implementations like this for a beginer? How do you go about this??
I think if you’re fundamentals are strong and understands classes and objects , you would be curious and would want to peek under the hood to see how “React” does it’s thing. It’s just something that you’d ask yourself naturally.
@@johnyepthomi892 I try going through the documentation sometimes but havent seen anyone really looking at the source code.
@@aswincg5895 I didn't say it's done by many, but for those that are experienced , I think this sort of thinking is eventually inevitable. Don't take it personally, it's not a n attack, I'm also not good at it. But I don't think my view is entirely wrong here. That's all from my side. Thank you. Please don't expect further response from me.
It is reassignment not mutation, the new state is a different ref completely. If something is mutated (ex: a) then if you do oldA===newA should return true, in this case its not the same because its not mutated its reassigned, and react decides to rerenders only if it gets a new ref, so if you have this.state={a:1} and u have onclick that changes a to 1 (you are not changing it since it was 1 already) Class based comp would still rerender because of new ref for the whole state(reassigned, not mutated). Whereas functional with hooks won’t rerender, because the value didn’t change. I’m glad u made a vid for more views and content
@@shreyashc So he is saying, that the component object is being changed, where as functions always get replaced with new ones. Duhh that's the point of functional programming vs oop.
I understood completely what he wanted to say, I was just trying to tell him to be more correct and specific in his words especially if the goal is for new people to understand.
In this case below example why the counter is working properly ? In case of setinterval example the counter was reinitializing to 0 again and again, but in below case why this is not happening? I am just curious to know. Can you exaplain this?
function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = () => {
setCounter(counter + 3);
};
return (
Increase counter
{counter}
);
}
export default App;
Thanks I did not know this at all before these 2 videos... Wish I ran into this before my last interview.
Is SSG in next.js with firestore getDocs not possible. I am trying it. I get result same way with fetch but getting const q = query(collectionRef, where("brand", "==", "PODS"));
> 40 | const podData = await getDocs(q); this second line gives me error
Loved the detailed explanation. Thanks 👍👍
Well explained. Bottom Line - Read source code Devs!
Plz explain why setInterval isn't working in useEffect as expected. Please 🙏
Add clean-up function which clears interval
watch it and cleared my doubt on why setinterval is not working same for functional component as it is for class based components...thanks man
Superb explanation 👌👏
Thank you! Subscribed :)
In my understanding of javascript, inst. state = nextState doesn't prevent object mutation like Object. assign({},inst.state, nextState) would do. But by initializing the state Object in the Class constructor, our state Object is defined and predictable, so we are just going to update the state without adding a new property to the state object (mutate it).
it would be great if someone could correct my way of thinking about it
13:27
I am a beginner in react how to make that work can anyone say?
How to create that setinterval effect with the functional component
Inside the setInterval method just this one liner is required-
setCount (prevCount => prevCount + 1)
This allows the setState method in a functional component to access the current state and then update it...
In the background this is because the set state method in a functional component doesn't mutate the state property of its inst object therefore we have to pass in the previous/current state value manually each time
@@zathkal4004
although this would work for simple state but for more complex state you can use `useReducer` because you have both state and actions/props at the hand to do your stuff, simply using `useState` won't work.
Additionally you can also write declarative way to implement `setInterval` for hooks.
Give "Making setInterval Declarative with React Hooks" by dan abramov a read, you will understand everything.
@@harshkc99 it was code for a beginner as mentioned by the initial commenter mate....
Moreover, obviously useReducer is the way to go while larger states involving the contextApi and so forth but like I said my answer was to a beginner.
Thanks anyway for your comment
So how do you mirror the behaviour of the class component state updation in the functional component useEffect hook for the particular scenario you just mentioned in the setInterval example ?? What's the solution? Can it not be done at all??
the previous value is passed to the function you put inside the setState.. setState(prevCount => prevCount + 1)
As always...Mehul Bhai thank you so much !!! Now I have one doubt due to this "Is this the reason why the functional component is not set the state just like class component does ? I mean we have to provide the previous state to setState for functional component because it returns the last state every time it re-renders".
Mehul sir, The state is NOT mutated. It's "Reassigned " . inst.state = {a:'' random variable'} will have a new reference is memory, thats why it will be rerendered.
I wish you would have compared the equality of both state while debugging, like you did for later. I am very sure, it would have returned false.
Nope, reassignment is NOT mutation. State never gets mutated in React. The general idea you're trying to convey is right - the component instance gets mutated, but all the people arguing that the state is not mutated were right. You were the one in the wrong, because what you said was a false statement.
Would you agree its correct to say, that state inside of usestate is mutated on every re-render?
😂 I like when people get triggered so I trigger them more
Do more videos like this on React JS. Interview Questions . Thanks for sharing.
I really enjoyed this in depth analysis of React. Very informative. Just a quick question, Here inst.state = newState, aren’t we mutating inst itself and not the state. Infact we are reassigning state by inst.state = newState and Hence mutating that particular instance but not the state property of that instance.
I understand the confusion too. IMO, it wouldn't be wrong to say that you are *also* mutating the 'state' property on *inst* object. That's what I meant when I said state is mutated. But I get your point.
@@codedamn I think I disagree :) By reassigning you're pointing to a new memory location which holds a different value. Mutation is when pointing to the same memory location but updating that value it holds, right? But anyway, very informative vids. Encouraged me to finally look into React's source code soonish.
Maybe it would've also been cool to mention, that count is a closure variable in the function based component (in the setInterval's anonymous fn). I think if you would put a console.log('render') in the function body, the component is indeed rerendered, but the state is always set to the same value in memory. Yeah but maybe that wouldn't haven been too relevant for the point you wanted to make.
how do you even have that much understanding? I want this level of knowledge but can it only be achieved by digging deep myself or I can get that level of information somewhere
Best explanation.
thank you sir..!
8:16 , true that inst is being mutated when its state property is triggered which was initially triggered by the state = value (value that state holds) getting reassigned
Using an objective approach I feel that the React team wanted to keep their documentation free of tech jargon in order to be beginner friendly as well I suppose, by simply meaning the following -
That a setState call would mutate the inst property eventually through its state property when the state's value gets reassigned.....
Just different wordings by the React team with the same goal in mind I guess...
Awesome job sir !
there is a difference between mutating vs reassigning a variable, they are not the same, in the source code they are clearly reassigning and not mutating inst
well done!
What was the point of these both videos?
React manage state for class and functional component different way. but it does not effect our devlopment or the core idea of using react.
The setimeout example is also wrong. you need to use prevState if you are updating a state with its own value.
useEffect(() => {
setTimeout(() => setTime((prevTime) => prevTime + 1), 1000);
});
for class component syntax would be different but idea remains same.
so just wanna know
if inst.state = nextState
and if nextState = {...inst.state, nextState} will that be mutation? How does nextState is calculated/computed?
I don't know anything about React (just learning and was wondering whether should do functional plus hooks or classes or both) and just from how he's misrepresenting what people say is enough proof for me that he has no idea what he's talking about. Class in JS is a function (he agrees) hence React Class is also a function (no because it's written different then a function). Fuck me... Also I like how people are pointing out something he said wrong, but no no guys, I didn't mean it like that. I oversimplified. Yeah, nice moving of the goalpost.
make video on nextjs 12 server components please
Mahul is a genius, but I think as a teacher he fails to convey his thoughts properly to students, I watched his lots of videos buy I always get confused, Maxmullian from acadamind is great at teaching, even normal student understand his stuff...
first of all clear me what do they mean by "mutation" exactly
This is so fun
Just something to add into your video.
const [counter, setCounter] = useState(1);
counter = 2;
raises Error is because you try to assign to a constant variable. I can't tell it's just a static checking without further investigation.
Since array in fact is an object in JavaScript;
const statehook = useState(1);
statehook[0] = 2;
this will pass the checking but it will definitely cause some runtime problem.
It's just the annoying traditional JavaScript object problem with `const` keywork.
Salty Indian W
🙏🔥
Nice
That's code was just for show. U even said it
People started to act dumb lmao 🤣
Clickbait
material ui 5 ua-cam.com/video/nVtk3EL-Q3s/v-deo.html
dude cut the chit, keep videos valuable(short), i frequently unsubscribe trashy youtubers
That is exactly why chapters exist in the video. I’m sorry sir but if your attention span is less than goldfish there’s no way to explain react internals in that small duration
@@codedamn boom roasted
BTW why are you here?