What is useRef? Why do we need to use it?

Namrata Sanja
2 min readJul 14, 2023

What is useRef?

useRef is a built-in React hook in a functional component. that allows creating reference to the DOM directly. The useRef returns a mutable ref object. useRef can be used to store a mutable value that does not cause a re-render when updated. useRef accept one argument as an initial value and returns a reference.

useRef is mainly used for creating reference of element that will not re-render on update.

Why do we need to use useRef?

The useRef Hook allows us to persist values between renders. it stores mutable value, on change that value component will not re-render. It can be used to access a DOM element directly.

In general, React handles all DOM manipulation. But there are some instances where useRef will use without causing issues and we can access elements directly from DOM.

We can get the previous value of the state, because we are able to presist value using useRef between render.

What is the benefit of using useRef in React?

the main benefit of using useRef is we can Reduce the re-renders, which improves the React application performance.

as useRef is storing mutable values, the component only re-render when some necessary changes are done.

useRef is reduicing unnecessary re-rendering component, which can lead to faster load times and a smoother user experience.

What is the difference between useState and useRef?

useState and useRef both are React hooks in the functional component.

the main difference is on a change of state value component will re-render unnecessarily, which affects the speed and load times of React application.

using useRef component will not load unnecessarily, which will reduce load time and make a smooth user experience.

When we need a value on the click of a button then we can use useRef for that as on click of a button only the component re-render and get value from input, but we need a value on input change for that we can use usestate on every key enter on input component will re-render, so we can get the updated value.

Hope this will helps you to understand that what is useRef and why do we need to use it

will create another blog for useRef in detail with example for better understanding.

If you have any questions regarding useRef or any other things in Javascript, React, and Redux. Please comment below. will create an article on it in detail.

Thanks for reading my article. Hope this helps you to know useRef in a better way. Follow me to learn more about react and redux in a better and easy way.

Happy coding … :)

--

--

Namrata Sanja

Web Developer. React, Redux (saga & thunk), Angular, React Native, Vuejs, gatsby, algolia, Antd, firebase