Published On: January 28th, 2023Categories: AI News

useRef() is similar to useSate() as it allows us to persist(remain unchanged) values between renders but unlike useState(), the Ref hook does not cause a re-render when the mutable value is changed.

useRef() returns a mutable object whose current property is set with an initial value that is passed as an argument to the Ref function.

const refObject = useRef(initial_value);

In the above example, refObject is the returned object. This object has a current property that can be used to obtain the value of the referenced object at any time.

There are two primary uses of useRef() –

  1. To create persisted mutable variables(these are called refs or references).
  2. To access DOM elements(or React elements).

Let’s dive into these.

1. useRef() to create persisted mutable variables

Trying to count the number of times a component re-renders using useState will lead to an infinite loop as useState itself causes a re-render. This is demonstrated in the example below.

import 

Source link

[gs-fb-comments]

Leave A Comment