Sushil Kumar’s Post

🧠 In React, what happens with this code? 👇 If userRef.current changes later, will the effect run again? 🤔 🗳️ Options 1️⃣ Yes, the effect will run again when userRef.current changes 2️⃣ No, it will only run once on mount 3️⃣ React will show a warning about using userRef.current in dependencies 4️⃣ It depends on how the ref is used ✅ Correct answer: 2 — the effect won’t re-run because React doesn’t track .current changes automatically. 💡 Why? Refs (useRef) are mutable containers that don’t trigger re-renders when they change. React does not track .current updates for dependency comparison — so adding userRef.current to the dependency array won’t behave as you might expect. #react #frontend #programming

  • text

Either wrong, or wrong exemple. Mutating directly userRef.current won't trigger useEffect. But the same as mutating a state won't trigger a re-render without a setState. Your exemple is wrong, because if the .current value is changed AND for another reason, the component is re-rendered, useEffect WILL compare previous and actual version of .current AND be triggered. If you don't want this behavior, userRef should be in dependency array, because its reference is stable among re-renders. (and because it's stable, you can exclude for the dependency array) Simple exemple for what i'm saying: A state with a counter, you assign the counter value to ref.current. A userEffect with ref.current as dependency array which simple do a console.log, and a button which increment the counter. useEffect is triggered at each re-render. https://codepen.io/hichtibidi/pen/myVYLLR?editors=1111 So correct answers are more 3 and 4 than 2 :)

To view or add a comment, sign in

Explore content categories