Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Ensure that nested fields where the path is defined by a variable trigger React.useMemo update when added to the dependency array

$
0
0

I use TypeScript 4 and React 17

I had this code in a custom hook:

  const myValue = useMemo((): string[] => {    if (someCondition) {      return (myMap?.field && myMap.field.[subfieldId]) || null    } else {      ...    }  }, [filter, filterIsValid, myMap.field.[subfieldId]])

ESlint complained that myMap.field.[subfieldId] had to be moved in a variable to be checked progammatically.

So I changed to this:

  const currentData: string[] | null = (myMap?.field && myMap.field.[subfieldId]) || null  const myValue = useMemo((): string[] => {    if (someCondition) {      return currentData    } else {      ...    }  }, [filter, filterIsValid, currentData])

I'm not sure that letting the variable in the upper scope, being recalculated at each rendering is a good practice, I'm even worried that an infinite loop could be created.

ESLInt suggest me to to this instead, that is much more simple:

  const myValue = useMemo((): string[] => {    if (someCondition) {      return (myMap?.field && myMap.field.[subfieldId]) || null    } else {      ...    }  }, [filter, filterIsValid, myMap.field])

Will myMap.field be enought for React to find out that myMap.field[subfieldId] change? I guess it shall be. Indeed, React will not know what changed if I only put myMap, because the object reference itself does not change, but when comparing the previous and the new myMap.field, React check all the sub-fields. Does it?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>