HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React useRef Hook

React useRef Hook

React useRef

'useRef' is a React Hook that provides a way to persist values across renders without causing the component to re-render when the value changes.

It returns a mutable object called a 'ref' object, which has a 'current' property that can be assigned any value.

Here are some common use cases for 'useRef':

1.Accessing and interacting with DOM elements:
import React, { useRef, useEffect } from 'react';

const MyComponent = () => {
const myRef = useRef(null);

useEffect(() => {
// Access and manipulate the DOM element
myRef.current.focus();
}, []);

return <input ref={myRef} />;
};

In this example, 'myRef' is used to get a reference to the 'input' element, and the 'useEffect' hook is used to focus on the input element when the component mounts.


2.Storing mutable values without triggering re-renders:

import React, { useRef, useEffect } from 'react';

const MyComponent = () => {
const counterRef = useRef(0);

useEffect(() => {
// Mutable value that won't trigger re-renders
counterRef.current = counterRef.current + 1;
console.log(counterRef.current);
}, []);

return <div>Check the console</div>;
};

In this example, 'counterRef' is used to store a mutable value ('0' initially) that can be modified without causing the component to re-render.


3.Preserving values across renders:
import React, { useRef, useState } from 'react';

const MyComponent = () => {
const previousValueRef = useRef();
const [value, setValue] = useState('');

const handleChange = (e) => {
setValue(e.target.value);
previousValueRef.current = e.target.value;
};

return (
<div>
<input type="text" value={value} onChange={handleChange} />
<p>Previous Value: {previousValueRef.current}</p>
</div>
);
};

In this example, 'previousValueRef' is used to preserve the previous value of the input field across renders without causing a re-render.