useRef vs. useState in React
React is a popular JavaScript library for building user interfaces. It provides several hooks that enable developers to manage state and perform side effects. Two commonly used hooks in React are useRef
and useState
. While they might seem similar at first glance, they serve different purposes and have distinct use cases. In this article, we will explore useRef
and useState
in depth, comparing their functionalities and providing examples to illustrate their usage.
Understanding useRef
:
The useRef
hook in React creates a mutable reference that persists across component renders. Unlike useState
, which manages state and triggers re-rendering, useRef
is primarily used to access and manipulate the DOM or to store mutable values that don't trigger re-renders. It returns a mutable object with a current
property.
Example 1: Accessing DOM elements
Let’s say we want to focus on an input field when a button is clicked. We can achieve this using useRef
as follows:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
In the example above, we create a ref
using useRef
and assign it to the inputRef
variable. We pass inputRef
to the ref
prop of the input element, making it available to access the input's DOM node. When the button is clicked, the handleClick
function is executed, and inputRef.current.focus()
is called to focus on the input field.
Understanding useState
:
The useState
hook is used to manage state within a functional component. It allows us to create variables that can be updated and trigger re-renders when their values change. The useState
hook returns an array with two elements: the current state value and a function to update it.
Example 2: Managing a counter
Let’s create a simple counter component using useState
:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
In the code above, we use the array destructuring syntax to assign the count
state variable and the setCount
function to update it. The initial value of count
is set to 0
using useState(0)
. When the button is clicked, the increment
function is called, updating the count
state by adding 1
. As a result, the component re-renders, reflecting the updated value of count
.
Comparing useRef
and useState
:
While both useRef
and useState
can store values, they serve different purposes:
- Managing state:
useState
is designed for managing state within a component. It triggers re-renders when the state updates, ensuring the UI reflects the latest values. - Accessing and manipulating the DOM:
useRef
is primarily used to interact with the DOM, such as accessing input values or focusing on elements. It allows us to store references to DOM nodes and retrieve their properties without triggering re-renders. - Preserving values across renders:
useRef
maintains the same value across component renders, whereasuseState
initializes the state during each render. - Re-rendering behaviour: Updating the value returned by
useState
causes the component to re-render, while updating thecurrent
property of aref
created withuseRef
does not trigger re-renders.
Use Cases:
To further understand the use cases of useRef
and useState
, let's explore some scenarios where each hook is more suitable:
1. useRef
Use Cases:
1.1. Accessing DOM elements: When you need to access or manipulate DOM elements, such as focusing an input, scrolling to a specific element, or measuring the size of an element, useRef
is the appropriate choice. It allows you to create a reference to the DOM node and access its properties or methods.
1.2. Storing mutable values: If you have a value that needs to persist across renders but does not affect the component’s UI or trigger re-renders, useRef
is a good option. For example, you can use useRef
to store previous values, caching values, or preserving mutable values for comparison.
2. useState
Use Cases:
2.1. Managing component state: When you need to manage and update state within a component, useState
is the recommended approach. It provides a way to store and update values that affect the component's UI and trigger re-renders.
2.2. Handling user interactions: If you have interactive elements in your component, such as checkboxes, input fields, or toggles, useState
is commonly used to manage the state associated with these interactions. You can update the state based on user input and reflect the changes in the UI.
Comparison Example:
To illustrate the difference between useRef
and useState
more clearly, let's consider an example where both hooks can be used:
Suppose we have a form with an input field and a submit button. When the user clicks the submit button, we want to display a success message without clearing the input field.
Using useRef
:
import React, { useRef } from 'react';
function Form() {
const inputRef = useRef(null);
const handleSubmit = () => {
const value = inputRef.current.value;
// Submit the form
displaySuccessMessage();
};
const displaySuccessMessage = () => {
// Display success message without clearing the input field
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
In this example, we use useRef
to create a reference to the input field. When the submit button is clicked, we access the value of the input field using inputRef.current.value
and proceed with submitting the form. The input field's value is not cleared because we are not updating the state or triggering a re-render.
Using useState
:
import React, { useState } from 'react';
function Form() {
const [inputValue, setInputValue] = useState('');
const handleSubmit = () => {
// Submit the form
displaySuccessMessage();
};
const displaySuccessMessage = () => {
// Display success message
setInputValue(''); // Clear the input field
};
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
return (
<div>
<input value={inputValue} onChange={handleInputChange} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
In this version, we use useState
to manage the state of the input field. We initialize the inputValue
state with an empty string using useState('')
. When the user types in the input field, the handleInputChange
function is called, updating the state and triggering a re-render to reflect the new value. When the submit button is clicked, the handleSubmit
function is executed, which displays the success message and clears the input field by setting the inputValue
state to an empty string.
In this example, useState
is used to manage the input field's value and trigger re-renders when the user interacts with it. The state update in displaySuccessMessage
clears the input field by updating the inputValue
state.
Conclusion:
In conclusion, useRef
and useState
are both essential hooks in React, but they serve different purposes. useRef
is primarily used to access and manipulate the DOM or store mutable values without triggering re-renders. It provides a mutable reference that persists across component renders. On the other hand, useState
is used for managing component state, triggering re-renders when the state updates. It returns a state value and a function to update it.
Understanding the differences between useRef
and useState
and knowing when to use each hook is crucial for writing effective and optimized React components. By utilizing useRef
and useState
correctly, you can build interactive and performant applications with React.
Thanks for reading!
I hope you found this article useful. If you have any questions or suggestions, please leave comments. Your feedback helps me to become better.
Don’t forget to subscribe⭐️
Facebook Page: https://www.facebook.com/designTechWorld1
Instagram Page: https://www.instagram.com/techd.esign/
Youtube Channel: https://www.youtube.com/@tech..Design/
Twitter: https://twitter.com/sumit_singh2311
Gear used:
Laptop: https://amzn.to/3yKkzaC
Watch: https://amzn.to/41cialm
You can prefer React Book: https://amzn.to/3Tw29nx
Some extra books related to programing language:
*Important Disclaimer — “Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”