[React] State and Callbacks Don’t Mix Well in React
// Doesn't work
import React from 'react'
import { saveInfo } from './api'
export default function App() {
const [count, setCount] = React.useState(0)
async function onClick() {
// because this is async api call
// react will wait until this api resolve
// during the waiting time, react component won't rerender
// therefore count will be 1
await saveInfo()
setCount(count + 1)
}
return (
<>
<h1>Count: {count}</h1>
<button onClick={onClick}>+1</button>
</>
)
}
Solution:
import React from 'react'
import { saveInfo } from './api'
export default function App() {
const [count, setCount] = React.useState(0)
async function onClick() {
await saveInfo()
setCount(count => count + 1)
}
return (
<>
<h1>Count: {count}</h1>
<button onClick={onClick}>+1</button>
</>
)
}
Even better:
import React from 'react'
import { saveInfo } from './api'
export default function App() {
const [count, setCount] = React.useState(0)
const inc = () => setCount(count => count + 1)
async function onClick() {
await saveInfo()
inc()
}
return (
<>
<h1>Count: {count}</h1>
<button onClick={onClick}>+1</button>
</>
)
}