Learn useRef in 11 Minutes
Why Stack Overflow recommends it
Stack Overflow users link it when explaining or asking about how useRef holds values across renders, including the previous-value pattern and render counting.
Recommended by 2 people across 2 different months, 2023 to 2024.
What it is
A short tutorial by Kyle of Web Dev Simplified on React's useRef hook. It covers storing values between renders, referencing DOM elements, and common mistakes, and ends with an example that tracks a previous state value.
What people said
Recommends Tengen Uzui · 2023-01 · Stack Overflow · on “How to make a container width bigger in React”
You can use a useRef hook and get the current width. This video [this video] will explain it better for you. In case you get stuck, feel free to reach out. After using the useRef , you can then use a ternery statement in the return statement to actualize the code.
Recommends Grease · 2024-01 · Stack Overflow · on “Query about useEffect hook in React”
So I was watching this yt video that explains how useRef works and there was this piece of code that was at the end of the video that puzzles me ( [this video] ) It basically uses a useRef to tell u what u previously typed in the textbox and what is currently typed into the textbox, but I dont understand why it works: import React, { useState, useEffect, useRef } from "react"; export default function App() { const [name, setName] = useState(""); const prevName = useRef(""); useEffect(() => { prevName.current = name; }, [name]); return ( <> <input value={name} onChange={(event) => setName(event.target.value)} /> <div> {" "} my name is {name} and it used to be {prevName.current} </div> </> ); } So
Cites jameswilson · 2023-10 · Stack Overflow · on “Trying to understand this useRef behaviour”
I get it now! Thanks for the clarification. However, I was seeing this video by Kyle: link [this video] @4:15 he writes a piece of code that makes use of useRef to keep track of how many times the component was rendered, and there the useRef variable isn't one behind. Wouldn't it be the same logic as the example I posted earlier? Sorry I can't paste the code here, it's too long for a comment.