4

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 ?

gkpo
  • 2,623
  • 2
  • 28
  • 47
  • Does this answer your question? [useEffect dependency only if a certain variable is present then only watch it as dependency](https://stackoverflow.com/questions/67603018/useeffect-dependency-only-if-a-certain-variable-is-present-then-only-watch-it-as) – Giorgi Moniava Aug 24 '22 at 11:26

1 Answers1

2

Syntax wise

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

Do you really need useMemo?

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.

Jonatan Kruszewski
  • 1,027
  • 3
  • 23