As we all know that javascript in the browser is all about accessing the DOM nodes and all we want to do is perform this function efficiently and smartly. In React, we have useRef hooks that help us access the DOM nodes directly and avoids unnecessary re-rendering of the entire component. The useRef hook will create an object with a single property: current and store the value of the element which is being referenced to inside this current property.
Let's explore an example where we'll make use of useRef hook and also demonstrate how it avoids unnecessary re-rendering of our React component.
Let's create a simple useRef hook in a React component in the following manner:
import React, {useRef} from 'react'
function UseRefDemo() {
const countRef = useRef(0);
const countClick= () => {
countRef.current++;
console.log(`Button was clicked ${countRef.current} times`);
}
console.log('Component rendered!')
return (
<div>
<h1>useRef Demo</h1>
<button onClick={countClick}>Click Me!!</button>
</div>
)
}
export default UseRefDemo
In the above component, we did the following actions:
- Defined a variable countRef using the useRef hook and set its initial value to 0
- Created a button and aim to count the number of times the button was clicked
- Defined a countClick function which will be called every time when the button is clicked.
- We are logging the current value of the button click using the current property: countRef.current and increment it every time the button is clicked.
- We also have a console.log statement that says 'Component rendered' which is printed out only once which demonstrates that this component is not re-rendered unnecessarily on every button click.
Now, if we run the above code with the useState hook where we define a count state variable and set it's initial value to zero but increment it by one on every button click, we'll see that the result is same but our component re-renders every time when the button is clicked since the console.log statement prints again and again:
import React, {useState} from 'react'
function UseRefDemo() {
const [count,setCount] = useState(0);
const countClick= () => {
const countClicks = count+1;
setCount(countClicks);
console.log(`Button was clicked ${countClicks} times`);
}
console.log('Component rendered!')
return (
<div>
<h1>useRef Demo</h1>
<button onClick={countClick}>Click Me!!</button>
</div>
)
}
export default UseRefDemo
If we run the above example, we'll see that the 'Component rendered' statement is printed out every time when the button is clicked:
There are other use cases also for the useRef hook which you can make use of, however this was just a basic comparison between useState and useRef hooks in React.
Hope you enjoyed reading and learnt something..
Happy coding...
Top comments (1)
Great! Thanks for sharing.