UseRef in React Explained Simply

When you want to persist values between renders, you use “a ref”.

First, you must add the ref to your component by import useRef Hook from React:

import { useRef } from 'react';

Call the useRef Hook and pass the initial value that you want to reference as the only argument.

const ref = useRef(0);

useRef returns an object that looks like this

{ 
  current: 0
}

This object is pretty much a secret backpack for your data that React does not change after re-renders. It is mutable as well meaning you can both read and write to it.

Accessing DOM in React (using Refs)

With most modern web frameworks, you aren’t actually manipulating DOM directly. In order to “directly” access the DOM in React, you must use API’s provided by developers.

To access DOM, import the useRef Hook:

import { useRef } from 'react';

Then, use it to declare a ref inside your component:

const myRef = useRef(null);

Finally, pass it to the DOM node:

<div ref={myRef}>

Initially, myRef.current will by null and React will load the value after the DOM has loaded. You can then access this DOM node however you like!

myRef.current.scrollIntoView();

Leave a Reply

Your email address will not be published. Required fields are marked *