E
E
eternalfire2019-12-26 12:07:04
css
eternalfire, 2019-12-26 12:07:04

How to update only one element of an array in Redux?

Hello!
I have a state in redux - an array of elements. Using a hook useSelector(), I get this array from redux

const places = useSelector(state => state.project.places);

Next I display this array
places.map((place, index) => (
    <Place
        key={index}
        place={place}
    />
));

When changing one element of the array, the entire table is re-rendered. Can you tell me how can this be avoided? Change one element of the array, and therefore one row in the table, and re-render only one row.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolay S., 2019-02-24
@Nikolays93

Take a look at Cloud 9 Carousel - 3D Carousel for jQuery and change the image (and/or image classes like animated) with js events.

M
Mikhail Osher, 2019-12-26
@eternalfire

Calling the render function does not mean redrawing the DOM. React will figure out what needs to be changed.
If you want "super performance", then you need to change the store structure to something like this:

const initialState = {
  result: [], // list of ids
  data: {}, // map by id
}

export const placesReducer = (state, { type, payload }) => {
  switch (type) {
    case 'PLACES_LOAD_SUCCESS':
      return {
        ...state,
        // псевдокод, можно использовать https://github.com/paularmstrong/normalizr
        result: payload.map(id),
        data: payload.reduce(keyById),
      }
  }
}

// по этому результату делаете .map
export const getPlaces = state => state.places.result
// этот селектор будет дергать каждый Place, только ему нынче кидайте не place={place}, а id={id}, ибо .map по идентификаторам идёт
export const getPlace = (state, id) => state.places.data[id];

Do not forget that in this way you create N + 1 subscriptions, and before there was 1 subscription.
React calls the render function (or the component function itself) a lot of times, so there is nothing to worry about in "extra" renders. Great post on this topic: https://kentcdodds.com/blog/fix-the-slow-render-be...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question