Can I pass array.map(val) => val
instead normal array as second argument to React.useMemo()
hook?
I'm receving a nested object from server as response and I can't give this response for second argument because useMemo()
just check instance of object, so I decided to map my response and return an array of some properties of child objects and pass them as an array for second argument of useMemo()
.
Is there better idea about this problem?
Is it ok to do such a thing?

- 65
- 7
1 Answers
You must pass an array to the memo second argument, so the answer is no.
But if you mean to pass an object to the dependency array, then it depends.
Will this object ever change? If the answer is yes your memo will change as well, and you may or may not want that.
Keep in mind that you can have two similar objects {foo: 'bar'}
and {foo: 'bar'}
that are different instances, so even if the server returns identical data twice the memo will be executed on each time. If that's what you want go ahead, use [{foo: 'bar'}]
as dependency.
If you do not want the memo to execute when the two objects are equivalent but not the same you must create some predictable primitive key out of the object, for example myObject.foo + myObject.bar
. Some people use JSON.stringify but I advise against that, JSON.stringify is not deterministic meaning you may get a different key each time stringifying identical objects
Here you can find some good read about the topic, it covers useEffect and useMemo and has an example with isDeepEqual as a workaround to compare if two objects are equivalent https://www.benmvp.com/blog/object-array-dependencies-react-useEffect-hook/

- 148
- 1
- 6