I have the following React snippet here
****** Example.js *******
import React from 'react';
export default const SampleApp = props => {
const [text, setText] = React.useState('Some name in here');
console.log(`[1] The value of the text is - ${text}`); // ---(1)
React.useEffect(() => {
setText('Ohhh yeah ma boy');
console.log(`[2] The value of the text is - ${text}`); // --- (2)
}, []);
React.useEffect(() => {
console.log(`[3] The value of the text is - ${text}`); // --- (3)
setText('Yare yare daze');
}, [text]);
console.log(`[4] The value of the text is - ${text}`); // --- (4)
return (
<div>{text}</div>
)
}
When i run it, it gives me the following console messages
[1] The value of the text is - Some name in here
[4] The value of the text is - Some name in here
[2] The value of the text is - Some name in here
[3] The value of the text is - Some name in here
[1] The value of the text is - Yare yare daze
[4] The value of the text is - Yare yare daze
[3] The value of the text is - Yare yare daze
[1] The value of the text is - Yare yare daze
[4] The value of the text is - Yare yare daze
I don't get it why 'Ohhh yeah ma boy' value did not appear in the console message?
Is it because of the same reason as to why the following code yields the value 5 5 5 5 5 on the console message when i run it though i expect it to show 0 1 2 3 4?
for (var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
Meaning that on the event loop, useState is already updated 2 times on the 2nd rerendering, while the second useEffect is still on queue?
