I am declaring a new variable called name and initializing it with useState to Math.Random() I then log the variable in 2 places, once in the body of the component, and once in the useEfect of the component. What I'm seeing is that the variable is changing.
My name is 0.1869175357793944 here My name is 0.10608469707774937 after render
Am I doing something wrong here? I cannot figure out why it's behaving like this.
Here is my code:
const {useState} = React;
const {useEffect} = React;
const Example = () => {
const [name, setName] = useState(Math.random());
console.log(`My name is ${name} here`);
useEffect(() => {
console.log(`My name is ${name} after render`);
}, [])
return (
<div>Look at console</div>
);
};
// Render it
ReactDOM.render(
<React.StrictMode>
<Example/>
</React.StrictMode>,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.development.min.js"></script>
<div id="react"></div>