Home >Web Front-end >JS Tutorial >Master DOM Manipulation and Performance with React useRef Hook
When building applications with React, one key challenge developers face is managing component state and performance. React’s useState hook is widely used for state management, but it can sometimes cause unnecessary re-renders. This is where the useRef hook becomes invaluable. It allows us to interact with the DOM directly, track changes, and store values without triggering component re-renders.
In this guide, we’ll explore the useRef hook step by step, covering its purpose, benefits, and common use cases. By the end, even a beginner will be able to confidently implement useRef to solve various challenges in their React applications.
The useRef hook is part of React’s core hooks API. It returns a mutable object with a .current property, which can be used to store any value you want. Unlike state, changing the .current value does not cause the component to re-render.
Here's the simple syntax for useRef:
const myRef = useRef(initialValue);
In React, state changes trigger re-renders. For performance-critical applications, excessive re-renders can slow down the app. Let’s take an example.
const MyComponent = () => { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); console.log("Button clicked"); }; return ( <div> <p>{count}</p> <button onClick={handleClick}>Increment</button> </div> ); };
In this example, clicking the button will cause the entire component to re-render, even though you might only care about updating specific data like the count.
With useRef, we can store values without causing unnecessary re-renders.
const MyComponent = () => { const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log("Button clicked, count: ", countRef.current); }; return ( <div> <button onClick={handleClick}>Increment</button> </div> ); };
In this example, we increment countRef.current without triggering a re-render, because React doesn’t re-render when useRef changes.
React’s declarative nature abstracts away direct DOM manipulations. But there are times when we need to access DOM elements directly, such as focusing an input field or scrolling to a particular section. This is where useRef comes to the rescue.
const myRef = useRef(initialValue);
In this example, we assign inputRef to the ref attribute of the input field. The handleFocus function is called when the button is clicked, allowing us to programmatically focus the input field using inputRef.current.focus().
Sometimes, you need to track values over time without triggering a re-render. A common use case is to track the previous state of a variable.
const MyComponent = () => { const [count, setCount] = useState(0); const handleClick = () => { setCount(count + 1); console.log("Button clicked"); }; return ( <div> <p>{count}</p> <button onClick={handleClick}>Increment</button> </div> ); };
In this example, we use useRef to store the previous value. The component renders with the current value, but the previous value is stored in prevValueRef.current and doesn’t trigger a re-render.
No, modifying a useRef object does not cause a re-render. This behavior makes useRef perfect for storing values that you need to persist across renders but don’t want to use as part of the rendering logic.
const MyComponent = () => { const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log("Button clicked, count: ", countRef.current); }; return ( <div> <button onClick={handleClick}>Increment</button> </div> ); };
In this example, even though we change renderCountRef.current on every re-render, it doesn’t cause any additional re-renders.
Let’s build a more advanced example where we count the number of times a button is clicked without causing re-renders.
const FocusInput = () => { const inputRef = useRef(null); const handleFocus = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={handleFocus}>Focus Input</button> </div> ); };
In this case, the button’s click count is tracked via clickCountRef.current, but React doesn’t re-render the component.
Always remember to initialize your ref with a value or null.
const PreviousStateExample = ({ value }) => { const prevValueRef = useRef(); useEffect(() => { prevValueRef.current = value; }, [value]); const prevValue = prevValueRef.current; return ( <div> <p>Current Value: {value}</p> <p>Previous Value: {prevValue}</p> </div> ); };
Do not use useRef as a substitute for useState. useRef should only be used for values that do not affect rendering. If the value affects the component’s display, use useState.
const NoRenderOnRefChange = () => { const renderCountRef = useRef(0); useEffect(() => { renderCountRef.current += 1; console.log("Component re-rendered:", renderCountRef.current); }); return <p>Check the console for render count</p>; };
Use useRef when you need to store a mutable value without triggering a re-render. For values that affect the UI, use useState.
Yes, you can use useRef to store previous values without triggering re-renders, but remember to update the reference in useEffect.
No, modifying useRef.current does not cause re-renders. That’s why it’s ideal for scenarios where you want to avoid unnecessary updates.
Assign useRef to the ref attribute of a DOM element, then you can access the DOM element via ref.current.
The useRef hook is a versatile and powerful tool in React that allows developers to store values, track previous states, and interact with DOM elements without causing re-renders. From managing click counts to focusing inputs, useRef opens up opportunities for optimizing performance and providing cleaner, more efficient solutions. With this guide, you now have the knowledge to implement useRef in various scenarios, from beginner-level use cases to more advanced applications.
The above is the detailed content of Master DOM Manipulation and Performance with React useRef Hook. For more information, please follow other related articles on the PHP Chinese website!