React Interview Question: State and Ref Behavior

🚨 React Interview Question (Advanced 🔥) What will be the output? 🤔 import { useState, useRef } from "react"; export default function App() { const [count, setCount] = useState(0); const ref = useRef(0); const handleClick = () => { setCount(count + 1); ref.current += 1; console.log("State:", count); console.log("Ref:", ref.current); }; return ( <button onClick={handleClick}> {count} | {ref.current} </button> ); } Looks simple… but there’s a twist 👀 👉 What will be: 1. Console output after first click? 2. UI value after click? Bonus: Why does "useRef" behave differently from "useState"? 🔥 #ReactJS #FrontendInterview #ReactHooks #useRef #JavaScript #ProductBasedCompany

State updates are async, so it logs the old value.Ref updates instantly, so it shows the new value. 👉 First Click (Console)State: 0Ref: 1 👉 UI After Render1 | 1 👉 Second Click (Console)State: 1Ref: 2 👉 UI After Render2 | 2 💡 Simple: state = async, ref = sync

Console Output - 0,1 (setcount is async, useRef is sync) UI - 1,1 (After re-render)

Like
Reply

Yes. state updates are async in nature so console log will print old value only

Like
Reply

If setCount(prev => prev +1 ); Is it will get same console output ?

Like
Reply

useState = Update UI useRef = Store value silently

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories