今日已更新 90 条资讯 | 累计 26894 条内容
关于我们

React Mastery Series – Day 14: React Hooks Deep Dive – Understanding useRef and useMemo

Siva Samanthapudi 2026年08月02日 02:49 0 次阅读 来源:Dev.to

Welcome back to the React Mastery Series ! In the previous article, we explored useEffect Hook and learned how React handles side effects such as: API calls Timers Event listeners WebSocket connections Cleanup operations Today, we will explore two more powerful React Hooks: useRef and useMemo These Hooks are frequently used in production applications to: Access DOM elements Store values without triggering re-renders Optimize expensive calculations Improve application performance Understanding useRef Hook useRef is a React Hook that allows us to store a value that persists across renders without causing the component to re-render. Syntax: const reference = useRef ( initialValue ); The returned object looks like: { current : initialValue } The value is accessed using: reference . current useRef vs useState A common question: Why do we need useRef when we already have useState? The difference: useState useRef Updates trigger re-render Updates do not trigger re-render Used for UI data Used for storing values React tracks changes React does not track changes Example: const [ count , setCount ] = useState ( 0 ); Updating: setCount ( count + 1 ); causes: State Update | ↓ Component Re-render With useRef: const count = useRef ( 0 ); Updating: count . current ++ ; does: Value Updated | ↓ No Re-render Using useRef to Access DOM Elements One of the most common use cases of useRef is accessing DOM elements directly. Example: import { useRef } from " react " ; function SearchBox () { const inputRef = useRef (); function focusInput () { inputRef . current . focus (); } return ( < div > < input ref = { inputRef } /> < button onClick = { focusInput } > Focus Input </ button > </ div > ); } Flow: Button Click | ↓ focusInput() | ↓ inputRef.current | ↓ Input DOM Element | ↓ focus() Real-World Example: Login Page Imagine a banking login page. When the page loads: Open Login Page | ↓ Username Field Automatically Focused Implementation: useEffect (() => { usernameRef . current . focus ();

本文内容来源于互联网,版权归原作者所有
查看原文