Ayoub Benayache
Ayoub Benayache

Reputation: 1164

how to prevent re-rendering components with redux

How to prevent component re-rendering, when i have an hierarchical array of objects (array of objects) using redux dispatching and memo for example i have like this list of list of components like

  Elements =[   // an array in store.state variable
                {name='a',
                 subEelemets:[
                              {name:'a-a', 
                              components:[
                                          {
                                           name:'a-a-1',
                                           component:'TextFiled',
                                            value:'default value...'
                                          },
                                          ]
                               },
                              ]
                 },
               ]

i used redux to update components values inside my Elements array using dispatch but the performance downgrades because of many re-rendering, i tried with memo to prevent re rendering but it also updates the entire Elements array because i used useSelector,

  const ImportedComponent = memo((props) => {

  const LoadableComponent = loadable(() =>
  import("../lib" + props.compName)) 
  );

  return (
    <LoadableComponent
      {...props}
       id={props.id}
  
     />)},(a,b)=>a.id===b.id?true:false) 

here the code how i redner my compoents

 const selectTodoIds = state => state.components.map((todo,index) => todo)

 const updateComp = () => {
    const Components = useSelector(selectCompsIds, shallowEqual)
  
    const renderedListItems = Components.map((CompId) =>
       <ImportedComponent key={CompId} elementID={CompId} />
    )
  
    return <ul className="todo-list">{renderedListItems}</ul>
  }

it works when i used a flat array as presented in the tutorial https://redux.js.org/tutorials/fundamentals/part-5-ui-react but not for hierarchical one, because i should use the "name" to define which subelement i'm updating, is there any strategy to solve this problem? ps: the code is just for clarification,

Upvotes: -1

Views: 89

Answers (1)

Adam Jenkins
Adam Jenkins

Reputation: 55623

Rather than memo you could try useMemo:

  const ImportedComponent = (props) => {

    const LoadableComponent = useMemo(() => {
      return loadable(() => import("../lib" + props.compName));
    },[props.compName]);
   
    ...

memo only helps when there's lots of re-renders with the same props, which it doesn't appear you have.

That's a complete shot in the dark, though. Can you post a link to a stackblitz, maybe? It'd be nice to see more of your code in context.

Upvotes: 0

Related Questions