Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
rsgmon Avatar asked Oct 22 '25 22:10

rsgmon


2 Answers

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.

like image 78
Dennis Vash Avatar answered Oct 24 '25 11:10

Dennis Vash


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.

like image 35
Force Bolt Avatar answered Oct 24 '25 12:10

Force Bolt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!