DEV Community

Cover image for Should you use useState or useRef?
Sajjat Hossain
Sajjat Hossain

Posted on

3 3

Should you use useState or useRef?

useState and useRef both are used to store component state in React. But there is a fundamental difference between them. They work differently.

useState copies the data and returns that data as state. On the other hand useRef stores the reference to that data. For better understanding let's see a simple example of what happens when we assign data to a variable in JavaScript. I found out that these two work exactly the same way (from my experience).

  • Example 1:
const value1 = [1, 2, 3, 4];
const value2 = value1;

console.log(value1) // [1, 2, 3, 4]
console.log(value2) // [1, 2, 3, 4]
console.log(value1 === value2); // true
Enter fullscreen mode Exit fullscreen mode
  • Example 2:
const value1 = [1, 2, 3, 4];
const value2 = [1, 2, 3, 4];

console.log(value1) // [1, 2, 3, 4]
console.log(value2) // [1, 2, 3, 4]
console.log(value1 === value2); // false
Enter fullscreen mode Exit fullscreen mode

Take a look at these examples. Two variables output same values but when comparing with each other, the output is different. Why does this happen?

It happens, because in the first case by declaring value1 = value2 we're assigning it a reference to value1. As the value2 is referencing to value1, it's like comparing value1 === value1 which is true cause the memory location is the same. Also in any given point of time, if you change the value of value2 then value1 will be changed too.
Image description

But in the second case, we're not referencing any variable to another. Their values are stored in their own memory location.
Image description

And while comparing, compilers aren't comparing values, instead comparing memory location. As the location is different, we're getting false as the output.

And this same situation occurs for the useState and the useRef hook.
So, if you need to store data then use useState hook and if you need to store reference to anything in the component, use useRef hook.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay