React useRef
useRef
keeps the value stored between renders.
In this, value changed doesn't cause a re-render.
It can also be used to access a DOM element directly.
Doesn't cause re-render
import { useState, useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const [stateValue, setStateValue] = useState("");
const refValue = useRef("");
return (
<>
<h1>Will cause a re-render:</h1>
<button onClick={() => { setStateValue(Math.random()) }}>state</button> : {stateValue}
<h1>Will change but won't cause a re-render:</h1>
<button onClick={() => { refValue.current = Math.random() }}>ref</button> : {refValue.current}
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
In this, if you click on state
button, state
will update and it will re-render, whereas if you click on ref
, nothing visible will happen, i.e. ref
will change but it won't re-render. To verify this, you can again click on state
, it will again update and re-render but this time ref
has some value stored, so that will display.
Accessing DOM elements with ref
import { useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
In this, we initialized a useRef
. In JSX, we used an attribute called ref
to store reference, once we have reference then we can use it anyway we want.