Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is it for the "current" key in useRef hook?

Reading the React documentation, there is a very useful hook to save the state or reference of a variable before the possible refresh of the component.

I understand perfectly this hook except for one question, and that is why it has to have a "current" value instead of being the variable that I want to save?

What I am expecting:

    const myVar = useRef('Hello world!');
    return <h1>{myVar}</h1>

What actually is:

    const myVar = useRef('Hello world!');
    return <h1>{myVar.current}</h1>
like image 666
mryuso92 Avatar asked Oct 29 '25 17:10

mryuso92


1 Answers

In React, changes in state force a component to re-render. A ref is for something you want to store that won't force a re-render even if does change. Typically, a DOM node.

Making this work requires a bit of indirection. The ref itself is always the same object. However the ref's properties - i.e. the current attribute - may change.

like image 56
David L. Walsh Avatar answered Nov 01 '25 07:11

David L. Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!