Reputation: 109
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:
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?
Upvotes: 0
Views: 825
Reputation: 62688
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.
Upvotes: 3