React useRef Hook
The useRef Hook is used to persist values between renders.
It does not cause a re-render when updated and can be used to store a mutable value, it also used to access a DOM element directly.
Below, is an example of useRef to keep the previous value of your state (name) after changing it.
import React, { useState, useEffect, useRef } from 'react';
export default function App(){
const [name, setName] = useState('')
const prevName = useRef()
useEffect(()=> {
prevName.current = name
},[name])
return (
<>
<input value={name} onChange={e => setName(e.target.value)}/>
<div> My name is {name} and it used to be {prevName.current}</div>
<>
)
}
Ref:
Top comments (0)