Menu

1 / 4

useRef Hook in react

DEV Community·Deva I·5 months ago
#g1drkAAm
#dev#useref#button#variable#state
Reading 0:00
15s threshold

useRef :

The useRef Hook allows you to persist values between renders.

It can be used to store a mutable value that does not cause a re-render when updated.

It can be used to access a DOM element directly.

Syntax :

import { useRef } from ' react ' ;

const myRef = useRef ( initialValue );

Enter fullscreen mode

Exit fullscreen mode

Important Points :

When you call useRef , it returns a plain JavaScript object with a single property called current .

The most important useRef is that changing its value does not trigger a component re-render.

Example Code :

import React from ' react '

import { useState , useRef } from " react " ;

function UserRef () {

let normalVar = 5 ;

const myRef = useRef ( 5 );

const [ count , setCount ] = useState ( 5 );

return ( < div > < p > Normal Variable: { normalVar } </ p > < p > Ref Variable: { myRef .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.