V
V
Vadim Stepanenko2021-09-01 15:54:18
React
Vadim Stepanenko, 2021-09-01 15:54:18

How can I optimize calculations in the react component?

Hey! There is a project on react + redux, on hooks the
Store looks something like this:

{
     items: [...],  // массив объектов с товарами, по типу { id: 1, title: 'hello', price: 100 }
     activeItemId: 1, // ID выбранного итема из массива items
}


In the product component, I get information about it in this way:
const activeItemId  = useSelector((state) => state.activeItemId);
const items  = useSelector((state) => state.items);

const activeItem = items.find((item) => item.id === activeItemId);


But as I understand it, the last line will be executed every time the component is re-rendered, which is generally not necessary. How can I cache(?) activeItem so that find doesn't get executed on every re-render?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-01
@Vadim1899

Usually items is made as an object, and then activeItem = items[activeItemId], this is very fast.
But if you need an array, then you can do this:

const activeItem = useMemo(() => items.find((item) => item.id === activeItemId), [items, activeItemId]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question