rsgmon
rsgmon

Reputation: 1932

Can a useMemo memoized value be updated with useEffect from within the component?

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?

Upvotes: 4

Views: 11072

Answers (2)

Force Bolt
Force Bolt

Reputation: 1221

You use useMemo and useEffect with the dependency of [] means it run during mounting means it run for once's

Let see How useMemo() works

  1. It will run every time if any change occur

    useMemo(()=>{

    })

  2. It will run once's during component mounting

    useMemo(()=>{

    },[])

  3. It will run every time if any changes occur in arr

    useMemo(()=>{

    },[arr])

If you have confusion what is the difference between useEffect() and useMemo()

useMemo() is only run when it find any changes it compare latest changes with the previous changes if it find any changes then useMemo run

useEffect() is run for every changes if the updated state is same as previous state useEffect don't care it start re render the component.

Upvotes: 3

Dennis Vash
Dennis Vash

Reputation: 53894

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.

Upvotes: 7

Related Questions