Created
January 11, 2022 18:24
-
-
Save salmanx/abe3f44db1efa9f1f73600f0ead3758d to your computer and use it in GitHub Desktop.
Persist previous state value after re render uing react useRef() hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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