Reputation: 139
I am little bit confuse about it! Is there any difference if we pass or don't pass null as an initial parameter in useRef? Like when we create state in functional component of React Js, we pass null as first value and then we update it! What if we also pass null in useRef like
const ref = useRef();
Or
const ref = useRef(null);
Both are correct?
Upvotes: 3
Views: 2824
Reputation: 396
Definition of useRef hook on React official doc is:
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
When you pass nothing i.e. useRef();
, the value assigned to the parameter will be undefined, and hence the value returned will be:
{current: undefined}
However, useRef(null);
will return
{current: null}
Upvotes: 1
Reputation: 169051
Both are correct but have different meanings.
const ref = useRef();
is (since unpassed parameters are undefined
) the same as
const ref = useRef(undefined);
so the initial value of the ref is undefined
, while with
const ref = useRef(null);
the initial value is null
.
Upvotes: 4