useRef
UseRef() is a hook provided by React that creates a mutable reference object which persists across renders of a functional component. It returns a single mutable value object ({current}) that can be updated without causing re-renders. useRef() is commonly used to access or store values that persist between renders without triggering component re-renders.
Example: Below is the code example:
// index.js
import React, { useRef } from 'react';
const Counter = () => {
const countRef = useRef(0);
// Initialize countRef with initial value of 0
const increment = () => {
countRef.current += 1;
// Increment the current value of countRef
updateCounter();
// Call updateCounter to update the displayed count
};
const reset = () => {
countRef.current = 0;
// Reset the current value of countRef to 0
updateCounter();
// Call updateCounter to update the displayed count
};
const updateCounter = () => {
// Update the counter displayed in the UI
document.getElementById('counter').innerText = countRef.current;
};
return (
<div>
<h2>Counter</h2>
<p>Count: <span id="counter">
{countRef.current}
</span></p>
<button onClick={increment}>Increment</button>
<button onClick={reset}>Reset</button>
</div>
);
};
const root = ReactDOM.createRoot(
document.getElementById('root')
);
root.render(
<div id='main_container'>
<div>
<img src=
'https://media.w3wiki.org/gfg-gg-logo.svg' alt='gfg_logo' />
</div>
<Counter />
</div>
);
Output:
Mastering Performance Optimization Techniques with React Hooks
In this article, we will explore advanced performance optimization techniques using React Hooks. We’ll delve into memoization, callback optimization, preventing unnecessary renders, state updates, and more. By mastering these techniques, developers can significantly enhance the performance of their React applications.