I'm working on a large react app where performance matters. At first I avoided using objects properties inside useMemo dependencies (I was avoiding dot notation inside dependencies). But I have seen this in react's documentation so I think it is safe. Now my linter sometimes complains when I don't include optional chaining inside the dependencies, and I end up doing this:
const artworks = useMemo(() => {
let list = availableArtworks.artworks;
if (route.params?.artworkId) {
// Some Stuff here
}
return list;
}, [availableArtworks, route.params?.artworkId]);
It looked dirty to me at first but now I'm considering starting to use it. If route
has no params
property, then the whole route.params?.artworkId
expression should be falsy, right? Then if the object changes, and we suddenly have a params
and artworkId
the useMemo should reexecute and take that value into account?
So my question is: Is it safe to use it like so or is it dirty in any ways ?
Looks safe. The one line I worry about is:
let list = availableArtworks.artworks;
If the key "artworks" isn't a primitive, you might modify it without intending to.
Also, your dependencies array should look like:
[availableArtworks?.artworks, route.params?.artworkId]);
Lastly, if performance is super important, I would definitely reconsider (and measure) if you do need the useMemo
. useMemo
is for heavy computational lifting. Do you have some recursion happening? Some intensive calculation? Factorials? Long Loops? If the answer is no, bringing useMemo
will in fact decrease performance.
Recommend you to read this article from Kent C. Dodds (Author of react-testing-library and remix) about performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With