How to Use React Refs with TypeScript

Refs provide a way to access DOM nodes or React elements created in the render method. Also, they can be used to store some references to entities or objects for accessing them later.

Using Refs with Functional Components#

To use refs with functional components use a special useRef hook.

It is a generic function, so we can pass a type-parameter, that will tell TypeScript what type is acceptable for this ref.

Initially, we set a ref's value as null, because it will be set later on render. That's why we need to null-check inputRef.current later in onFocus.

Also, inputRef itself is an object that contains a value in the current field. So to access the real element we need to get a value of this field.

Using Refs with Class Components#

In class components, you can store refs in private class fields after creating them with createRef.

Using Refs to Store Objects#

When you need to access some data but you don't need to share it across components and don't need to change it you can use refs too.