Search code examples
javascriptreactjsreact-ref

what time does reactJS reference useRef Hook variable to html element having ref attribute?


I am starting learning about useRef in ReactJS. I have a question about what time ReactJS replace the initialValue ( which we pass when define useRef ) by the Dom node (that contains ref attribute). I have run code following but result does not like what i guess :

enter image description here

Before running the code, i predict that:

result of line 7 is before: {current: '1'} {current: '2'}

result of line 15 is after: {current: <h1>Hello world</h1>} {current: <p>happy coding</p>}

And i think that at line 15 reactJS have updated value of refH1 and refP (reactJS update value of refH1 and refP at line 10 and 11 respectively)

However the result of the code is:

before: {current: '1'} {current: '2'}

after: {current: '1'} {current: '2'}

Therefore i have a question that What time does ReactJS replace initialValue by Dom node for useRef Hook?


Solution

  • https://react.dev/learn/manipulating-the-dom-with-refs

    When React creates a DOM node for this , React will put a reference to this node into myRef.current

    So it's when html element is created. Not when jsx element is created.