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

1.4k Views Asked by At

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!

3

There are 3 best solutions below

0
On BEST ANSWER
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])
0
On

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.

0
On

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])