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#
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
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#
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.