const myRef = useRef(initialValue);
const value = myRef.current;
import React, { render, useRef, useEffect } from "react";
const DomRefDemo = () => {
const inputRef = useRef(null);
useEffect(() => {
// Focus the input field on component mount
inputRef.current.focus();
}, []);
return (
<div>
<h1>useRef Example: DOM Access</h1>
<input
ref={inputRef}
type="text"
placeholder="I will be focused on load" />
</div>
);
};
render(<DomRefDemo />);
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
import React, { useRef, useState, render } from "react";
const MutableRefDemo = () => {
const renderCount = useRef(1);
const [count, setCount] = useState(0);
// Increment renderCount on each re-render
renderCount.current += 1;
return (
<div>
<h1>useRef Example: Mutable Values</h1>
<p>
Re-rendered: {renderCount.current} times
</p>
<p>State Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment Count
</button>
</div>
);
};
render(<MutableRefDemo />);
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
import React, { useRef, useState, useEffect, render } from "react";
const PreviousValueDemo = () => {
const [count, setCount] = useState(0);
const prevCount = useRef(count);
useEffect(() => {
prevCount.current = count; // Update the ref value after render
}, [count]);
return (
<div>
<h1>useRef Example: Preserve Previous State</h1>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCount.current}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
render(<PreviousValueDemo />);
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
Feature | useRef | useState |
---|---|---|
Triggers Re-render | ❌ No | ✅ Yes |
Mutable | ✅ Yes (via
current
)
|
✅ Yes (but causes re-render) |
Usage | DOM access, persisting values | State management, triggering re-renders |