# Refs & useRef

> How to remember values between renders without triggering a new render, and how to access raw DOM elements.

Subject: React | Lesson 18 of 48 | 5 min read
Interactive lesson: https://codewithanimation.in/react/refs-and-useref
Previous: [Strict Mode](https://codewithanimation.in/react/strict-mode.md) | Next: [Controlled vs Uncontrolled](https://codewithanimation.in/react/controlled-vs-uncontrolled.md)

## What is a Ref?

A Ref (short for reference) is an 'escape hatch' in React.

When you call `useRef(initialValue)`, React gives you back a plain JavaScript object with a single property: `{ current: initialValue }`.

You can read from or write to `ref.current` at any time. **Crucially, changing `ref.current` does not trigger a re-render.**

## State vs. Refs vs. Variables

Why not just use a regular variable? If you write `let count = 0` inside your component, it gets reset to `0` every single time the component re-renders.

Why not just use state? If you use `setState`, React will re-render the entire component. If the value doesn't actually affect what is shown on the screen (like a timer ID, or previous scroll position), re-rendering is a massive waste of performance.

Refs are the goldilocks solution: they survive re-renders (like state), but they don't *cause* re-renders (like variables).

## The two main use cases

**1. Storing mutable data:** Tracking timeout IDs, keeping track of how many times an effect has run, or storing previous state values.

**2. Accessing DOM Elements:** If you pass a ref to a JSX element (`<input ref={myRef} />`), React will put the actual browser DOM node into `myRef.current`. You can then call native methods on it, like `myRef.current.focus()`.

## Common mistake: The screen isn't updating!

The most common mistake is trying to display a ref's value in your JSX, like `<div>{countRef.current}</div>`.

Because updating a ref doesn't tell React to re-render, the user clicks a button to increment the ref, the ref updates in memory, but the screen stays exactly the same. Only use state for data that goes on the screen!

## Tip: Synchronous Updates

Unlike state updates, which are queued and asynchronous, ref updates are completely synchronous. The exact millisecond you write `myRef.current = 5`, the value is immediately available to read on the very next line of code.

## Try it: The Three Memory Types

Click the buttons to increment the values. Notice how the 'Local Variable' is wiped out on every render, the 'State' triggers a render immediately, and the 'Ref' silently remembers its value in the background.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/refs-and-useref

## Check yourself

### Question 1

What is the primary difference between `useState` and `useRef`?

- A. `useState` survives re-renders, while `useRef` gets reset every render.
- B. Updating `useState` triggers a component re-render, while updating `useRef` does not.
- C. `useRef` can only store strings, while `useState` can store any data type.

Correct answer: B

Refs are for 'under the hood' data that shouldn't cause the UI to repaint when it changes.

- Why not A: Both survive re-renders.
- Why not C: Both can store any JavaScript data type.

### Question 2

How do you programmatically focus an `<input>` element in React?

- A. Use `document.getElementById('my-input').focus()`.
- B. Create a ref, pass it via `<input ref={myRef} />`, and then call `myRef.current.focus()`.
- C. Pass a boolean state variable `<input isFocused={true} />`.

Correct answer: B

Passing a ref to a JSX element tells React to attach the underlying DOM node to the ref's `.current` property once it is rendered.

- Why not A: While this works, it violates React's declarative model and can break in complex apps.
- Why not C: The standard DOM input does not support an `isFocused` prop.

### Question 3

You have `<p>Score: {scoreRef.current}</p>`. A button click runs `scoreRef.current += 1`. What happens?

- A. The screen updates to show the new score.
- B. The score updates in memory, but the screen does not change.
- C. React throws an error because refs cannot be rendered in JSX.

Correct answer: B

Because modifying a ref doesn't trigger a render, React doesn't know it needs to update the `<p>` tag. If it's on the screen, it should be state!

- Why not A: Refs do not trigger re-renders.
- Why not C: It's legal to render them, but they won't update reactively.

## Remember this

- `useRef` returns `{ current: initialValue }`.
- Updating a ref does not trigger a re-render.
- Refs survive re-renders (unlike normal variables).
- Use state for things you see; use refs for things you calculate.
- Pass a ref to a JSX element to get direct access to the DOM node.
