React - useMemo has a complex expression - Extract it to a separate variable so it can be statically checked

Viewed 6317

I'm trying to use useMemo but a I got a message from lint:

React Hook useMemo has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked react-hooks/exhaustive-deps.

What could it be?

const [selectedDate, setSelectedDate] = useState("Escolha uma data para pagamento");
const itens = useMemo(() => {
  if (!contrato.propostas || contrato.propostas.length == 0) return [];
  let dates = contrato.propostas.map(p => p.vencimento)
  dates = Array.from(new Set(dates)).map((item) => ({
    id: item,
    option: item
  }))
  if (dates.length === 1 && selectedDate !== contrato.filterByDate) setSelectedDate(dates[0].option)
  if (contrato.filterByDate && dates.find(d => d.id === contrato.filterByDate) !== -1) setSelectedDate(contrato.filterByDate);
  return dates;
}, [JSON.stringify(contrato.propostas), contrato.filterByDate, selectedDate])

contrato and contrato.propostas are objects.
contrato.filterByDate is a string.
I tried to find an open question but I couldn't find one.

1 Answers

It's telling you to do this:

const [selectedDate, setSelectedDate] = useState("Escolha uma data para pagamento");
const temp = JSON.stringify(contrato.propostas);
const itens = useMemo(() => {
 // ...
}, [temp, contrato.filterByDate, selectedDate])

But i don't see why you're stringifying contrato.propostas. You never use the stringified version, so it's not actually a dependency. And as long as you're keeping your data immutable (as you should in react), then you just need to put contrato.propostas directly into the dependency array:

const [selectedDate, setSelectedDate] = useState("Escolha uma data para pagamento");
const itens = useMemo(() => {
 // ...
}, [contrato.propostas, contrato.filterByDate, selectedDate])
Related