The argument provided to useRef
is the initial value that gets set for the ref.
const someRef = useRef(true);
will result in an object
{
current: true
}
and
const someRef = useRef(false);
will result in an object
{
current: false
}
For the useIsMountedRef
function, it:
- Initializes a ref with a value of
true
- The effect hook with an empty dependency array runs only once, after the component mounts. A function returned from an effect hook callback runs when the component unmounts. So this
useEffect(
() => doSomething,
[]
);
means: "run doSomething when the component unmounts".
Here. doSomething
is
() => {
isMounted.current = false;
}
or: "Set the value in the isMounted ref to false when the component unmounts."
For the second code, an effect hook with a dependency array of [dependency]
will mean that the callback runs both on mount, and right after a render whenever dependency
changes. So
if (!mounted.current) {
mounted.current = true;
} else {
// code
}
Whenever dependency
changes or the component mounts:
- If the ref isn't set to true, it'll be set to true
- Otherwise, the other
// code
will run
Because it looks like no function was returned from that useEffect
, unlike the other code, this code will not run something when the component unmounts - it'll only run when the component first mounts, and during a re-rendering that included a change to dependency
.
Read the docs on useRef
.