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.
let val = 1, ref = { current: val }; setTimeout(() => { ref.current++; }, 1); console.log(val, ref.current);
If you guessed1 2
you'd be wrong. – Patrick Roberts