Skip to content

Instantly share code, notes, and snippets.

@salmanx
Created January 11, 2022 18:24
Show Gist options
  • Save salmanx/abe3f44db1efa9f1f73600f0ead3758d to your computer and use it in GitHub Desktop.
Save salmanx/abe3f44db1efa9f1f73600f0ead3758d to your computer and use it in GitHub Desktop.
Persist previous state value after re render uing react useRef() hooks
export default function UseRef() {
const [name, setName] = useState('');
const renderCount = useRef(1);
const prevName = useRef('');
useEffect(() => {
renderCount.current = renderCount.current + 1
prevName.current = name;
})
return(<>
<input type="text" onChange={(e) => setName(e.target.value)} />
<p>My name is {name} </p>
<p>I got rendered {renderCount.current} times</p>
<p>My name is now {name} but I used to be {prevName.current} </p>
</>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment