useRef: DOM Access & Persistence
Mission
Use useRef to reach DOM elements directly and to keep values that survive renders without causing new ones.
Tasks
- 1
Create a ref with
useRef(null)and attach it to the<input>with therefattribute. - 2
Make the first button focus the input using the ref (
.focus()). - 3
Create a second ref that starts at
0to count clicks on the 'secret' button. - 4
Increase that count on every click without using
useState. - 5
Report the count with an
alertorconsole.log, not on screen.
import React, { useRef } from 'react'; export default function RefDemo() { // 1. Create a ref for the input // 2. Create a ref to count clicks (starts at 0) const focusInput = () => { // 3. Focus the input using the ref }; const secretIncrement = () => { // 4. Increase the ref's count, but do not use useState // 5. Show an alert with the current value of .current }; return ( <div style={{ padding: '20px', textAlign: 'center', fontFamily: 'sans-serif' }}> <h1>Working with Refs</h1> <input placeholder="Type something here..." style={{ padding: '10px', marginBottom: '10px' }} // 6. Attach the ref here /> <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}> <button onClick={focusInput}> Focus input </button> <button onClick={secretIncrement}> Secret click (no re-render) </button> </div> <p style={{ marginTop: '20px', color: '#666' }}> Check the console: secret clicks do not trigger a render. </p> {console.log("Component rendered...")} </div> ); }
Requirements
0/6A useRef(null) is attached to the <input> (not run yet)
Calls .focus() through the ref's .current (not run yet)
A second ref starts at 0 to count clicks (not run yet)
The counter does not use useState (not run yet)
Increments the counter's .current (not run yet)
Reports the value with alert or console.log (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.