Vibe coding with Claude Code course ยท Module 3: Twitter clone
The captain's notebook: useRef in the post form
In this lesson8
The captain writes several posts in a row and keeps losing the rhythm. After clicking "Send" the cursor escapes from the field, so before the next post you have to click into the field again. And when the feed grows and you scroll far down, you go back to the form with the mouse wheel. Both problems come down to one order for the browser: "put the cursor in this field". The state from lesson 2_3 will not give it, because state describes what to draw, not where the cursor stands.
useRef in one paragraph
This is what useRef is for, another React hook. Calling useRef(initialValue) returns an object with a single property current, and useRef(0) gives { current: 0 } at the start. React hands you the same object on every render, so whatever you store in it survives. The most important difference from state: changing current does not refresh the screen.
In lesson 2_3 state was the logbook, where every entry is a sign for the crew that something changed. A ref is the notebook in the captain's pocket: the captain writes in it whatever he wants, but nobody aboard finds out. A notebook is useful for two things: remembering where a particular element of the page stands, and holding values you do not show on screen.
Request for Claude Code
The change touches one file and has a clear shape, so it needs no plan. The last sentences of the request protect what already works.
Request for Claude Code:
In @components/Feed.tsx: 1) after a post is sent, put the cursor back
in the textarea so I can write the next one right away; 2) add a
"Write a post" button pinned to the bottom right corner of the screen,
which moves the cursor to the field from anywhere in the feed. Use
useRef and explain in your answer why a ref and not state. Do not touch
the draft state and the character counter. At the end run npm run build
and npm run lint.The request for an explanation is a test for Claude: if it cannot say why a ref and not state, it probably picked the tool blindly.
What Claude wrote: a notebook for the post field
Open components/Feed.tsx. Below the posts and draft states one line was added, and at the top of the file useRef joined the imports from react:
const textareaRef = useRef<HTMLTextAreaElement>(null);The type in angle brackets says which element the ref will point to: HTMLTextAreaElement is a <textarea> field in the browser. The initial value is null, because on the first render the field is not on the page yet. The ref itself points at nothing until you attach it to an element.
Attaching is one attribute on the form field from lesson 2_3:
<textarea
ref={textareaRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}The ref attribute tells React to put the real element into textareaRef.current when the field appears on the page, and to clear it back to null when it disappears. value and onChange stay in place: the field is still controlled by state.
The cursor returns to its place
At the end of handleSubmit, after clearing the field, Claude added one line:
setPosts([newPost, ...posts]);
setDraft("");
textareaRef.current?.focus();focus() is a built-in method of an element in the browser: it puts the cursor in it. By default the browser also scrolls the page so that the field is visible. The ?. calls the method only when current holds an element and not null. Here it is honest caution, because an empty ref before the field is drawn is an expected state; in lesson 2_8 you will see ?. used to sweep an error under the rug.
Claude placed the "Write a post" button at the end of the section, with the class fixed bottom-6 right-6, which pins it to the corner of the screen. Its click handler is the same line: onClick={() => textareaRef.current?.focus()}. Thanks to the default scrolling, one click takes you from the bottom of the feed straight to the field.
Controlled or uncontrolled field
A field with value and onChange is the controlled form from lesson 2_3: React knows its content on every render. There is also a second way. An uncontrolled field gets only defaultValue, the starting content, and the browser keeps the current value. You read it through a ref only on submit, for example textareaRef.current.value. This is handy in a simple form from which you need the value once, on confirmation.
Our field stays controlled, because the counter and the disabled button need the content on every render. The one exception with no choice is <input type="file">: the value of a file field cannot be set from a script, only the user chooses it, so such a field is always uncontrolled and you read it through a ref. It matters that one field does not mix both ways: value and defaultValue at once is a mistake. In the editor below you will check how refs behave: the button sets focus, the counter in a ref grows without changing the screen, and the message field is uncontrolled and gives back its content only on submit.
Code for this lesson: App.jsx
// useRef: focus, a value without re-rendering and an uncontrolled field
import { useRef, useState } from 'react';
export default function App() {
const inputRef = useRef(null);
const clicksRef = useRef(0);
const [log, setLog] = useState('');
const handleFocus = () => {
inputRef.current.focus();
};
const handleRefClick = () => {
// Changing a ref does not update the screen
clicksRef.current = clicksRef.current + 1;
};
const handleSubmit = (e) => {
e.preventDefault();
// Uncontrolled field: we read the value from the DOM only on submit
setLog('Message: ' + inputRef.current.value + ' (clicks stored in the ref: ' + clicksRef.current + ')');
inputRef.current.value = '';
};
return (
<div className="min-h-screen bg-slate-900 p-8 text-white">
<h1 className="text-3xl font-bold mb-6">useRef on deck</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<input
ref={inputRef}
defaultValue=""
placeholder="Message to the crew"
className="w-full p-3 rounded text-black"
/>
<div className="space-x-2">
<button type="button" onClick={handleFocus} className="bg-blue-600 px-4 py-2 rounded">
Set focus
</button>
<button type="button" onClick={handleRefClick} className="bg-amber-600 px-4 py-2 rounded">
+1 to the ref (the screen will not change)
</button>
<button type="submit" className="bg-green-600 px-4 py-2 rounded">
Send
</button>
</div>
</form>
<p className="mt-6">{log}</p>
</div>
);
}A ref does not refresh the screen
Claude explained the choice roughly like this: the cursor is a matter for the browser, not the look of the page, so there is nothing to draw again. The same sentence works the other way round. Everything that is meant to appear on screen has to live in state.
A typical agent mistake: Claude "optimises" the form. It writes that the draft state refreshes the component on every letter, so it makes the field uncontrolled and keeps the content in a ref:
const draftRef = useRef("");
// ...
<span>{draftRef.current.length}/{MAX_LENGTH}</span>Letters appear in the field, because the browser holds them, but the character counter stands still: changing draftRef.current does not trigger a render. The React docs say plainly not to read or write ref.current during rendering, except to set the initial value: do it in event handlers or in effects. npm run lint guards this rule with react-hooks/refs and reports the error Cannot access refs during render. When you see it, ask to go back to state, not to silence the rule.
Captain's review
Before you commit, check in the browser and in the diff:
- The cursor after sending. Send a post and keep writing right away, without clicking. The letters should land in the field.
- The button from the bottom of the feed. Scroll the page down and click "Write a post": the page returns to the form, and the cursor stands in the field.
.currentonly in event handlers. In the JSX and in the component body there is no read oftextareaRef.current, andnpm run lintpasses withoutreact-hooks/refserrors.- No
forwardRef. When the field sits in its own component, in React 19 you pass the ref like an ordinary prop. The React docs sayforwardRefis no longer needed and will be deprecated, and Claude sometimes reaches for it from older code.
Next step
Ask for a commit with a message like "Focus the post field after sending and add a Write a post button". Then the other side of the notebook, a value you cannot see:
After a post is sent, show a "Post added" message below the form in
@components/Feed.tsx, which disappears after 3 seconds. When I send
a second post earlier, the countdown should start over.The message goes into state, because it is visible on screen. The timer number from setTimeout is not visible, but the send function has to know it at the next post, so Claude hides it in the notebook:
setNotice("Post added");
if (noticeTimerRef.current) clearTimeout(noticeTimerRef.current);
noticeTimerRef.current = setTimeout(() => setNotice(""), 3000);noticeTimerRef is created next to the state as useRef<ReturnType<typeof setTimeout> | null>(null), a notebook for the timer number or for nothing. clearTimeout stops the old countdown before the new one starts, so a second post does not lose its message a second after sending. Changing current does not refresh the screen and does not need to: the screen is changed by setNotice. In the editor below waits the form from this lesson: send two posts quickly one after another and click "Write a post".
Remember: the logbook calls the crew together, and the notebook in the captain's pocket works quietly.
Code for this lesson: App.jsx
// A post form with the captain's notebook (useRef):
// textareaRef points at the field, and noticeTimerRef remembers the timer number.
// Send two posts quickly one after another, scroll down and click "Write a post".
import { useRef, useState } from 'react';
const MAX_LENGTH = 280;
const crewPosts = [
'Kraken spotted near Skull Island. Sailing west.',
'Rudder fixed. Who will help with the sails?',
'Fish soup for dinner. First come, first served!',
'The treasure map is drying on deck.',
'The boatswain is looking for volunteers to scrub the deck.',
'The gulls stole the hardtack again.',
];
export default function App() {
const [posts, setPosts] = useState([]);
const [draft, setDraft] = useState('');
const [notice, setNotice] = useState('');
const textareaRef = useRef(null);
const noticeTimerRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
if (!draft.trim() || draft.length > MAX_LENGTH) return;
setPosts([{ id: String(Date.now()), content: draft.trim() }, ...posts]);
setDraft('');
// A ref in an event handler: the cursor returns to the field
textareaRef.current?.focus();
// The message in state, the timer number in a ref
setNotice('Post added');
if (noticeTimerRef.current) clearTimeout(noticeTimerRef.current);
noticeTimerRef.current = setTimeout(() => setNotice(''), 3000);
};
return (
<div className="min-h-screen bg-gray-50 p-6 pb-24 text-gray-900">
<h1 className="text-3xl font-bold">Crew feed</h1>
<form onSubmit={handleSubmit} className="mt-4 rounded-lg border border-gray-300 bg-white p-4">
<textarea
ref={textareaRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}
rows={3}
placeholder="What's new aboard?"
className="w-full rounded border border-gray-300 p-2"
/>
<div className="mt-2 flex items-center justify-between">
{/* The counter is computed from the draft state on every render */}
<span className={draft.length > MAX_LENGTH * 0.9 ? 'text-sm text-red-600' : 'text-sm text-gray-500'}>
{draft.length}/{MAX_LENGTH}
</span>
<button
type="submit"
disabled={!draft.trim() || draft.length > MAX_LENGTH}
className="rounded bg-blue-600 px-4 py-2 font-semibold text-white disabled:opacity-50"
>
Send
</button>
</div>
{notice && <p className="mt-2 text-sm text-green-700">{notice}</p>}
</form>
<ul className="mt-4 space-y-4">
{posts.map((post) => (
<li key={post.id} className="rounded-lg border border-blue-300 bg-white p-4">
<p className="font-bold">Captain Redbeard</p>
<p className="mt-2">{post.content}</p>
</li>
))}
{crewPosts.map((content) => (
<li key={content} className="rounded-lg border border-gray-300 bg-white p-4">
<p className="mt-2 h-24">{content}</p>
</li>
))}
</ul>
<button
type="button"
onClick={() => textareaRef.current?.focus()}
className="fixed bottom-6 right-6 rounded-full bg-blue-600 px-5 py-3 font-semibold text-white shadow-lg"
>
Write a post
</button>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the call useRef(0) return?
2. Claude replaced the draft state with useRef to save renders: the field is now uncontrolled, and the character counter reads draftRef.current. What will you see?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the tokens that put the cursor back in the textarea after a post is sent: