Last active
December 9, 2020 15:42
-
-
Save d12/9fd61841c93045eb6727b21ffd62c158 to your computer and use it in GitHub Desktop.
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
// 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