Skip to content

Instantly share code, notes, and snippets.

@onosendi
Created January 31, 2022 05:14
Show Gist options
  • Select an option

  • Save onosendi/3b99b4d39a14516cd8f2e1aaf042dc45 to your computer and use it in GitHub Desktop.

Select an option

Save onosendi/3b99b4d39a14516cd8f2e1aaf042dc45 to your computer and use it in GitHub Desktop.
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