I am working on a React coding challenge (problem link) and the solution is here.
In the problem, the custom hook returns true for the first render, otherwise returns false.
import { useRef } from "react";
export function useIsFirstRender(): boolean {
const isFirstRender = useRef(true);
if (isFirstRender.current) {
isFirstRender.current = false;
return true;
}
return false;
}
In the codes above, I don’t get the way to declare this function. What exactly useIsFirstRender(): boolean {} means?
And since isFirstRender.current is defined as true in the function, It sounds like it will return true at any renders.
Do I misunderstand the usage of useRef? Thank you!
2
Answers
the
: boolean
is the return type, the data type of the value that this function returns. This is TypeScript syntax and is not part of JavaScript itself.As for
useRef(true)
, thetrue
is the initial value.useRef
allows you to use persistent values between renders. So your if-statement should work and betrue
on the first timeuseIsFirstRender()
is called and befalse
every time after that.That’s TypeScript code, not JavaScript code. The
: boolean
part means it returns aboolean
value.isFirstRender.current
isn’t alwaystrue
.useRef
gives you a mutable ref object, and it always gives you the same mutable ref object on every call (for thatuseRef
in that hook/component). (The ref object is stored in the instance information of the component this hook is being called by.) In the first call, it initializes the ref object’scurrent
property with the value you provide touseRef
, but it only does that during the first call, not subsequent calls. If you can change thecurrent
value (as you see that code does), that change endures from call to call. That’s one of the points of refs: They let you store instance-specific, durable information connected to the lifecycle of the element the function component (or the hooks it calls) are managing.Here’s an example with some logging that may help clarify it (using just JavaScript, not TypeScript):
Notice how the
isFirstRender.current
value is onlytrue
the first timeuseIsFirstRender
is called for the mounted element, not for subsequent calls.