Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent React from re-rendering a specific child component

I have a react component that conditionally renders several child components. Simplified code is just:

render(): {
  const component1 = condition ? renderComponent2() : null;
  const component2 = renderComponent2();

  return (
    <div>
      {component1}
      {component2}
    </div>
  );
}

The problem is that component2 is getting destroyed and re-rendered whenever the condition changes. I'm trying to prevent that and keep the original element around. I tried adding a key to component2 with no luck.

[edit] This is happening even when component1 always exists and I change flag on it to hide it or not with CSS :/

like image 383
Nobody Avatar asked May 27 '16 00:05

Nobody


People also ask

How do you prevent re-rendering of a child component in react?

If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.

How do you prevent re-rendering of a component when there is a change of state in parent component but no change in its own component?

If the child component is re-rendered without any change in its props then it could be prevented by using hooks. React. memo is the savior, it is a higher-order component that memorize remembers) the result i.e. React will skip rendering of that component and reuse the last rendered result. It checks for prop changes.


1 Answers

Have you tried doing it with shouldComponentUpdate? This is exactly what this function should be used for. Just add it to your component2 and add proper condition inside.

like image 68
Ales Maticic Avatar answered Oct 04 '22 21:10

Ales Maticic