I'm trying to render data that must be passed through useMemo
. I get the data from an api call so I call useEffect
. The initial render works returning an empty array but once I call the api, data is not updated.
import React from 'react'
import {fetchAccounts} from '../utils/api'
export default function Accounts() {
const [accounts, setAccounts] = React.useState([])
React.useEffect(() => {
setLoading(true)
fetchAccounts().then((data) => {
setAccounts(data)
})
}, [])
const data = React.useMemo(() => accounts, [])
return <p>{JSON.stringify(data)}</p>}
So can this work within a single component? Or must a custom hook be created?
The data is not updated because you missing a value in the dependency array.
const data = React.useMemo(() => accounts, [accounts]);
Therefore in this case, it does not make sense to use useMemo
since the state is stable anyways, till you change the state.