Here is my react hooks code:
function Simple(){
var [st,set_st]=React.useState(0)
var el=React.useRef(null)
if (st<1)
set_st(st+1)//to force an extra render for a grand total of 2
console.log('el.current',el.current,'st',st)
return <div ref={el}>simple</div>
}
ReactDOM.render(<Simple />,document.querySelector('#root') );
I thought it should render twice. the first time el.current should be null and second time is should point to the DOM object of the div. when running this, this was the output
el.current null st 0
el.current null st 1
It did, yes, render twice. however, the second render th el.current is still null. why?
solution: as described by Gireesh Kudipudi below. I added useEffect
function Simple(){
var [st,set_st]=React.useState(0)
var el=React.useRef(null)
if (st<1)
set_st(st+1)//to force an extra render for a grand total of 2
console.log('el.current',el.current,'st',st)
React.useEffect(_=>console.log('el.current',el.current,'st',st)) //this prints out the el.current correctly
return <div ref={el}>simple</div>
}
ReactDOM.render(<Simple />,document.querySelector('#root') );