Created
January 31, 2022 05:14
-
-
Save onosendi/3b99b4d39a14516cd8f2e1aaf042dc45 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import { useRef, useState } from 'react'; | |
| export default function Foo() { | |
| // When we change the state, we cause the component to re-render. | |
| const [count, setCount] = useState(0); | |
| // This gets persisted between re-render | |
| const persisted = useRef(null); | |
| // This does not get persisted between re-render | |
| let notPersisted = null; | |
| const handleClick = () => { | |
| setCount(count + 1); | |
| persisted.current = 'foo'; | |
| // We're changing the component's state with `setCount` which causes | |
| // a re-render. Even though we're setting this variable, it's getting | |
| // lost due to the re-render. | |
| notPersisted = 'foo'; | |
| }; | |
| return ( | |
| <> | |
| <p>{`Count: ${count}`}</p> | |
| <p>{`Persisted between re-render: ${persisted.current}`}</p> | |
| <p>{`Not Persisted between re-render: ${notPersisted}`}</p> | |
| <button | |
| onClick={handleClick} | |
| type="button" | |
| > | |
| Cause Re-Render | |
| </button> | |
| </> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment