If you want to store or update value without rendering the component then useRef is the best solution.
It is also commonly used to access DOM elements like input field, buttons and other html elements.
Syntax:
const myRef = useRef(initialValue); useRef is a React hook
myRef is a reference variable
initialValue is a initial vaue
How does useRef work?
When you call useRef(), React creates a reference object with a property called current.
For example:
const myRef = useRef(10);
console.log(myRef);
Here, myRef is an object, and current is its property.
You can access the value using:
console.log(myRef.current);
Store a Value Without Re-rendering
Let's see how useRef stores and updates values without re-rendering the component.
import React, { useRef } from 'react';
function App() {
const count = useRef(0);
function Increase() {
count.current++;
console.log(count.current);
}
return (
{count.current}
Increase
);
}
export default App;
Explanation
Initially, the count value is 0.
When we click the button, count.current increases by one.
The updated value is displayed in the console.
However, the heading does not update because changing current does no
