0
votes

Today, if we want to save react from re rendering a sub part of a parent component1, we have no other choice but to create a component2 nested in component1 and implement shouldComponentUpdate for component2.

It is very useful. But in my case, my apps are very little likely to be written with multiple nested components since every DOM part is unique. Splitting my app into components would be very verbose and error prone. So I only have a main component for a page with an inline DOM in the render function. But at the same time, depending on my app state, there are big DOM nodes (static inline svg for example) I want to save from re rendering.

My idea is to be able to use a kind of "unicityKey" that would tell react "Okay, the unicityKey has not changed", no need to go any deeper in this node, it hasn't changed. For example :

<div unicityKey={...} key={"myKeyIfNecessary"} >
    content
</div>

would be the inline version exactly equivalent to:

<Component2  unicityKey={...} key={"myKeyIfNecessary"} />

with

class Component2 extends React.Component{  

  shouldComponentUpdate(nextProps, nextState) {

    return this.props.unicityKey != this.nextProps.unicityKey;  

  }  

  render() {

      return (

        <div>content</div>    

      );

    } 

};

any idea how I could achieve this while keeping inline DOM (so without creating a component2 ..) ?

2
This cannot be implemented without using component such as Component 2. - Igor Stetsiura

2 Answers

0
votes

Surely, making a single component do this is not too much:

class Component2 extends React.Component {

  shouldComponentUpdate(nextProps, nextState) {
    return this.props.unicityKey != this.nextProps.unicityKey;  
  }

  render() {
    return this.props.children;
  }
}

Or even:

class Component2 extends React.PureComponent {
  render() {
    return this.props.children;
  }
}

Then you just need to do:

<Component2 unicityKey={...} key={"myKeyIfNecessary"}>
  content
</Component2>

This will handle any case you like.

0
votes

Ok in the meantimes Kevin Raoofi almost answered my question. I had no idea about HOC and possibility to do content and to define the wrapper...but it possible ! So i have defined:

class Wrapper extends React.Component {
  shouldComponentUpdate(newProps){
    return this.props.unicity_key != newProps.unicity_key;
  }
  render() {
    return (this.props.children);
  }  
}

and I use it in my render:

<Wrapper key={...} unicity_key={this.state.questions_displayed+"_"+this.state.ticked_box} >
 stuff which are not re rendered has long as unicity_key hasn't changed...
</Wrapper>

Nice and easy !