Using the ref Hook
In this section, we will learn about the ref Hook and where it is useful. We will then walk through a common use case of the ref Hook by enhancing the PersonScore
component we have been working on.
Understanding the ref Hook
The ref Hook is called useRef
and it returns a variable whose value is persisted for the lifetime of a component. This means that the variable doesn’t lose its value when a component re-renders.
The value returned from the ref Hook is often referred to as a ref. The ref can be changed without causing a re-render.
Here’s the syntax for useRef
:
const ref = useRef(initialValue);
An initial value can optionally be passed into useRef
. The type of the ref can be explicitly defined in a generic argument for useRef
:
const ref = useRef<Ref>(initialValue);
The generic argument is useful when no initial value is passed or is null
. This is because TypeScript won’t be able to infer the type correctly.