I am new to React and have a hard time understanding why when I call useEffect after I just set the new state on a variable, the new value is undefined. Can someone also explain why the second UseEffect hook is called twice. Is it because it's called on initial mount, and then called when it finally changes state from the first useEffect? How can I get it to fire only once val has a defined value that was set in the first useEffect?
import React from 'react';
import {useState, useEffect} from 'react'
export function App(props) {
const [val, setVal] = useState();
useEffect(() => {
setVal("hello");
},[]);
useEffect(() => {
console.log("value: ", val);
}, [val])
return (
<div className='App'>
</div>
);
}
The code is working exactly as I'd expect it to.
On (or more specifically, immediately after) the first render, both effects execute. Which:
undefined to the consoleThen when state is updated, the component re-renders. This re-render has a new state value for val, which triggers the second useEffect to execute. Which:
"hello" to the consoleHow can I get it to fire only once val has a defined value that was set in the first useEffect?
If you want something to happen conditionally, you'd use an if statement. For example:
useEffect(() => {
if (val) {
console.log("value: ", val);
}
}, [val])
This will only log val to the console if it has a "truthy" value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With