REACT
React Ref: Syntax, Usage, and Examples
React refs give you direct access to DOM elements or component instances without triggering re-renders. They are useful for handling focus, animations, measuring elements, and integrating with third-party libraries. You can create refs using React.createRef()
in class components or useRef()
in functional components.
How to Use React Ref
React provides two main ways to create and use refs.
Using React.createRef()
in a Class Component
import React, { Component } from "react";
class InputField extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
focusInput = () => {
this.inputRef.current.focus();
};
render() {
return (
<div>
<input type="text" ref={this.inputRef} />
<button onClick={this.focusInput}>Focus Input</button>
</div>
);
}
}
Using useRef()
in a Functional Component
import React, { useRef } from "react";
function InputField() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
Both approaches allow direct interaction with the <input>
element without triggering re-renders.
When to Use React Ref
Accessing DOM Elements Directly
Refs help when you need to access a DOM element without updating the component state. You might use them for focusing an input field, controlling animations, or measuring an element’s size.
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
Storing Values Without Causing Re-Renders
Unlike state, updating a ref does not trigger a re-render. This makes refs useful for tracking values that need to persist between renders, such as previous values or render counts.
const count = useRef(0);
useEffect(() => {
count.current += 1;
console.log("Render count:", count.current);
});
Managing Third-Party Libraries
When working with non-React libraries like D3.js, Chart.js, or jQuery, refs allow direct access to elements.
import { useEffect, useRef } from "react";
import Chart from "chart.js";
function ChartComponent() {
const canvasRef = useRef(null);
useEffect(() => {
new Chart(canvasRef.current, {
type: "bar",
data: { labels: ["A", "B"], datasets: [{ data: [10, 20] }] },
});
}, []);
return <canvas ref={canvasRef} />;
}
Examples of React Ref in Practice
Managing Focus in Forms
You can use refs to focus an input field when a user submits a form.
function Form() {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
alert("Form submitted!");
inputRef.current.focus();
};
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} type="text" placeholder="Type here..." />
<button type="submit">Submit</button>
</form>
);
}
Persisting Values Without Causing Re-Renders
When tracking values across renders without updating the UI, use refs instead of state.
function Timer() {
const count = useRef(0);
useEffect(() => {
const interval = setInterval(() => {
count.current += 1;
console.log("Seconds passed:", count.current);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Check the console for the timer.</p>;
}
Handling Scroll Position
Refs can track scroll positions and help adjust UI behavior.
function ScrollComponent() {
const divRef = useRef(null);
const scrollToBottom = () => {
divRef.current.scrollTop = divRef.current.scrollHeight;
};
return (
<div>
<div ref={divRef} style={{ height: "100px", overflowY: "scroll" }}>
<p>Some long content...</p>
<p>More content...</p>
</div>
<button onClick={scrollToBottom}>Scroll to Bottom</button>
</div>
);
}
Learn More About React Ref
Forwarding Refs to Child Components
By default, refs do not work on custom components. If you want to pass a ref to a child component, use forwardRef()
.
import React, { forwardRef, useRef } from "react";
const CustomInput = forwardRef((props, ref) => (
<input ref={ref} {...props} />
));
function Parent() {
const inputRef = useRef(null);
return (
<div>
<CustomInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
React Props vs. Ref
Props pass data between components and trigger re-renders when updated. Refs provide a way to reference an element without causing a re-render.
Use refs when you need to:
- Manage focus, animations, or measurements.
- Track component lifecycle events.
- Store mutable values across renders.
Use props when you need to:
- Pass data between components.
- Trigger updates in the UI.
Using Refs in Functional and Class Components
Functional components use useRef()
to manage refs, while class components use React.createRef()
. Both methods allow direct manipulation of elements but do not cause re-renders.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.