Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import { useRef, useEffect, useState } from 'react'; function AutoFocusInput() { const inputRef = useRef(null); // Focus the input after mount useEffect(() => { inputRef.current?.focus(); }, []); return <input ref={inputRef} placeholder="I get focus on mount" />; } function StopwatchWithRef() { const [elapsed, setElapsed] = useState(0); const intervalRef = useRef(null); // stores timer ID – NOT state function start() { if (intervalRef.current !== null) return; // already running const startTime = Date.now() - elapsed; intervalRef.current = setInterval(() => { setElapsed(Date.now() - startTime); }, 10); } function stop() { clearInterval(intervalRef.current); intervalRef.current = null; } return ( <div> <p>{(elapsed / 1000).toFixed(2)}s</p> <button onClick={start}>Start</button> <button onClick={stop}>Stop</button> </div> ); }
Result
Open