React Mastery / React Core Concepts

Refs

🧠 What are Refs in React?

Refs (short for References) in React give you a way to directly access and interact with DOM elements or component instances.

Think of Refs like saying:

“Hey React, please give me a handle to this element so I can do something with it directly.”


💡 Why use Refs?

Normally in React, you let the framework manage everything. But sometimes you need direct control — like:

  • Focusing an input field

  • Playing/pausing a video

  • Getting the value of an input without using state

  • Measuring the size or position of an element


🧩 Syntax — How to Create and Use a Ref

✅ Import the tools

import React, { useRef } from 'react';

✅ Create a ref using useRef()

const myInputRef = useRef(null);

✅ Attach it to an element using ref={...}

<input type="text" ref={myInputRef} />

✅ Use it (e.g., focus the input on button click)

const focusInput = () => {
  myInputRef.current.focus();
};

📦 Full Example

💬 What’s happening here?

  • inputRef is a reference to the <input> element.

  • When the button is clicked, inputRef.current.focus() puts the cursor inside the input box.


🔁 Summary

Concept

Explanation

useRef()

Creates a ref

ref={myRef}

Connects ref to an element

myRef.current

Accesses the actual DOM element

Common Use Cases

Focus input, scroll to element, etc.