I have trouble understanding React states and useEffect in this particular example. I have 2 initial states, word which is initialized as empty string, and field that gets value from a function initField()
initField function returs concated string that is word + 'FIELD'
function initField(){
console.log("CALLED")
return word+ ' - '+ "FIELD"
}
after changing states in useEffect hooks, I expected the output of the field to be "WORD - FIELD" but the output I get is only "- FIELD"
I cant understand why is that happening, can someone give deep explanation ?
This is my full code
function App() {
const [word,setWord]=useState('');
const [field,setField]=useState(initField())
function initField(){
console.log("CALLED")
return word+ ' - '+ "FIELD"
}
useEffect(()=>{
setWord("WORD");
setField(initField());
},[])
return (
<div className="App">
<h1>{field}</h1>
</div>
);
}