useState vs useRef in React: Understanding the Difference

𝐑𝐞𝐚𝐜𝐭 𝐇𝐨𝐨𝐤𝐬 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers use useState and useRef… but don’t know the real difference. Question: What is the difference between useState and useRef? And which one causes re-render? Example 👇 import React, { useState, useRef } from "react"; export default function App() { const [count, setCount] = useState(0); const refCount = useRef(0); console.log("Render"); return ( <> <button onClick={() => setCount(count + 1)}> useState + <button onClick={() => { refCount.current += 1; console.log(refCount.current); }}> useRef + </button> </> ); } What happens here? Click useState button → Component re-renders Click useRef button → Component does NOT re-render Why? useState → updates state and re-renders component useRef → updates value without re-render Tip for Interview: useRef is used for storing mutable values without causing re-render. Good developers know hooks. Great developers know when to use them. #ReactJS #ReactHooks #useState #useRef #FrontendDeveloper #JavaScript #ReactInterview #CodingInterview #WebDevelopment

  • graphical user interface

To view or add a comment, sign in

Explore content categories