React.js useRef hook not returning the expected object

Bahman :

I'm using React hooks and I have the code below:

const [_va, _setva] = useState(0);
const va = useRef({current: _va});
console.log(va);

So according to the documentation, The expected value of va is an object which has a current property containing the desired value which is initially 0.

But when I run the script I got this result:

result

In other words, instead of the va.current containing the desired value, va.current contains another current property which contains the desired value. Which means I have to access va.current.current to access the desired value.

Does anyone know why this happens?

Chris Heald :

You've misunderstood the doc; you will set the value of the ref, and it is returned in the current property of the returned object:

const ref = useRef("foo");
console.log(ref.current) // "foo"

The purpose of useRef is to give you an object whose reference does not change, but whose value may. That value is exposed as current. You can access and reassign ref.current at will, and ref remains unchanged.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31898&siteId=1