0
votes

I was practicing useRef usage with useEffect hook. Simply, it shows the old value since useEffect hook runs after React paints the UI.

function UseRefExample1() {
const ref = useRef('')
const [val, setVal] = useState('')

useEffect(() => {
    ref.current = val
}, [val])

return (
    <div className='Home'>
        
        <input type='text' value={val} onChange={e => setVal(e.target.value)}/>
       <p>my current value - {val} - my old value - {ref.current}</p>
       
    </div>
)
 }

export default UseRefExample1

I wanted to test the same code with useLayoutEffect since it fires synchronously after all DOM mutations and right before React paints the UI. And, I expected to see current value placeholder and old value placeholder same, but the output is not different from useEffect hook usage.

function UseRefExample2() {
const ref = useRef('')
const [val, setVal] = useState('')

useLayoutEffect(() => {
    ref.current = val
}, [val])

return (
    <div className='Home'>
        
        <input type='text' value={val} onChange={e => setVal(e.target.value)}/>
       <p>my current value - {val} - my old value - {ref.current}</p>
       
    </div>
   )
}

export default UseRefExample2

If someone can explain the reason why useLayoutEffect hook does not make current value and old value same, I would be thankful.

What would you expect this output to be? let val = 1, ref = { current: val }; setTimeout(() => { ref.current++; }, 1); console.log(val, ref.current); If you guessed 1 2 you'd be wrong.Patrick Roberts
@PatrickRoberts I understand your point, but what I dont understand is behavior of useLayoutEffect. I expected that after a key stroke, value is updated, component rerenders but before ui updates uselayouteffect hooks runs its code and browser shows ref.current same as val. Otherwise, I understand how useEffect runs.Özgür