useState vs useRef - When should we use them?
Tags: react, hooks
Published: 2023-01-31 18:57:18

As a React Developer, I have come across this question many times and for a long time. One is probably the most used (as of React 16.8), the other one is perhaps more difficult to find in repositories of developers who are just starting their career (I include myself). 
That's why the goal of this post is to analyze each hook, see their similarities and differences, pros and cons and the best scenarios to use each one.


## useState, pros and cons

_**useState**_ is a hook in React that allows you to add state to a functional component. It returns an array with two elements, the first being the current state value, and the second being a function to update the state.

**Pros of useState:**
- Easy to use and understand
- Triggers re-render and updates component when state changes

**Cons of useState:**
- Can cause re-renders and slow down the performance of the app if not used properly
- Not ideal for values that should persist across re-renders


## useRef, pros and cons

_**useRef**_ is a hook that allows you to access and manipulate a value that will persist across re-renders without triggering a re-render. It returns a mutable object whose. Current property is initialized to the passed argument (or null).

**Pros of useRef:**

- Ideal for values that should persist across re-renders
- Can improve performance by avoiding unnecessary re-renders

**Cons of useRef:**

- More difficult to use and understand than useState
- Not reactive, does not trigger re-render or updates component when the value changes.

## When should we use useState instead useRef?

It is better to use useState when you need to manage a value that should trigger a re-render and update the component when it changes.

```
import React, { useRef, useState } from 'react';

const Example = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment Count</button>
    </>
  );
};

export default Example;

```
In this example, we want to increment a count when a button is clicked. Since the count should trigger a re-render and update the component when it changes, we can use useState to manage the count value. This ensures that the component is re-rendered and updated when the count changes. If we used useRef here, the component would not re-render when the count changes and the updated count would not be reflected on the screen.


## When should we use useRef instead useState?

It is better to use useRef when you need to access or manipulate a value that should persist across re-renders without triggering a re-render. For example, when accessing DOM elements, storing intervals, or creating a value that should persist across re-renders.

```
import React, { useRef, useState } from 'react';

const Example = () => {
  const inputRef = useRef(null);
  const [value, setValue] = useState('');

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} value={value} onChange={e => setValue(e.target.value)} />
      <button onClick={handleClick}>Focus Input</button>
    </>
  );
};

export default Example;

```
In this example, we want to focus on an input element when a button is clicked. Since the focus method is a DOM property and doesn't trigger a re-render, we can use useRef to store a reference to the input element and then call the focus method on it when the button is clicked. This avoids having to store the focus property in state and triggering unnecessary re-renders.

## Conclusion

In conclusion, both **useState** and **useRef** hooks serve different purposes in React and the choice between them depends on the specific needs of the component.

**useState** is useful for managing values that should trigger a re-render and update the component when they change.

**useRef** is useful for accessing or manipulating values that should persist across re-renders without triggering a re-render.

When deciding which hook to use, it's important to consider whether the value should trigger a re-render or persist across re-renders, as well as the **performance implications** of each choice. Both hooks can be used in combination to achieve the desired behavior in a given component.