简体   繁体   中英

How to memoize a value based on a property of an object in React?

In my functional component, I want to memorize some value which depends on Id property of an object:

obj={
  innerProperty:{
    id:1
  }
}
useMemo(()=>someComplaxFunction(), [obj.innerProperty.id])

I want to do something like this, but the issue is, innerProperty can be undefined . So I need to add a check for innerProperty, but I cannot add that outside useMemo as it gives me error that hooks should not be called conditionally and not even inside as then I will have to add obj as dependency which I don't want because other properties may change.

Need to know how can I achieve this. Any help is appreciated.

Thanks in advance!

obj={
  innerProperty:{
    id:1
  }
}
const id = obj.innerProperty ? obj.innerProperty.id : undefined

// or using optional chaining(?.)
const id = obj.innerProperty?.id

useMemo(()=>someComplaxFunction(id), [id])

Inside your someComplaxFunction() check the value of innerProperty and return something like null so that you memorized value is null in this case (or anything else you want). And then use the memorized value in your component assuming that it could potentially be null .

Guess you shoud do some check. You can't do that logic inside ur dependecies array, but you can do something that way:

useMemo(()=> {
    if (obj.innerProperty.id) {
        someComplaxFunction()
    }
}, [obj.innerProperty])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM