Skip to content

Instantly share code, notes, and snippets.

@d12
Last active December 9, 2020 15:42
Show Gist options
  • Save d12/9fd61841c93045eb6727b21ffd62c158 to your computer and use it in GitHub Desktop.
Save d12/9fd61841c93045eb6727b21ffd62c158 to your computer and use it in GitHub Desktop.
// Doesn't work
function Component(props: Props) {
[foo, setFoo] = useState<number>(0);
function useFoo() {
// Foo is always 0
console.log(foo);
}
return <>
<p>{foo}</p>
<button onClick={() => setFoo(foo + 1)}>Increment foo</button>
<button onClick={useFoo}>Use foo</button>
</>;
}
// Works
function Component(props: Props) {
// Gross, I have to update both the ref and the state
[foo, setFoo] = useState<number>(0);
fooRef = useRef<number>(0);
function useFoo() {
console.log(foo.current);
}
return <>
<p>{foo}</p>
<button onClick={() => { setFoo(foo + 1); fooRef.current = foo + 1 }>Increment foo</button>
<button onClick={useFoo}>Use foo</button>
</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment