0% found this document useful (0 votes)
2 views

Document_useRef

Uploaded by

go.coronago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Document_useRef

Uploaded by

go.coronago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 4

UseRef hook:

1. What is it?

useRef is a React Hook that lets you reference a value that’s not needed for rendering.It allows us to
store values that are mutable but doesn't cause re-render.

Syntax: const ref = useRef(initialValue)

2. What is the real time scenario for this hook ?

While working with forms and you want to focus on your text field on any error or when we load the
page we can make use of useRef hook to refer to that particular DOM element.

For example:

import { useEffect, useRef } from "react";

export default function App() {

let inputRef = useRef();

useEffect(() => {

inputRef.current.focus();

}, []);

return (

<>

<input ref={inputRef} type="text" />

</>

);

3. What benefit we get from it.

One of the benefit's of useRef hooks is that changes to it doesn't trigger re-renders of the component.
This makes useRef an excellent choice for storing values that you want to persist across re-renders but
don't want to cause re-rendering.
4. When do I use it?

UseRef are mostly use when you want to access and manipulate the DOM or store mutable values
without triggering re-renders.

5. How to use it??

const ref = useRef(initialValue);

import { useEffect, useRef, useState } from "react";

export default function App() {

let ref = useRef(0);

const [value, setValue] = useState(0);

useEffect(() => {

console.log("Re-render");

});

function handleClick() {

ref.current = ref.current + 1;

alert("You clicked " + ref.current + " times!");

function handleClickB() {

setValue(value + 1);

return (

<>

<button onClick={handleClick}>Click me!</button>

<button onClick={handleClickB}>Click me!</button>


</>

);

Output:

Initial Render:

On Click of first button:

On CLick of second button:

You might also like