0
votes

I have this tree of components:

Father
    Son
        Childrens
    Daughter
        Childrens2
    Modal

Everytime that Modal is open (by setting this.setState({ openSimpleModal: true });) or it's close (setting state as false) the componentes Son, Daughter, and their childrens components are re-rendered to. Is there a way where I can open and close the Modal, but not allowing to re-render 1 specific component, for example, Son (and their childrens) but re-rendering the rest? (Daughter, etc) but ONLY when the Modal opens or close. I need to render each child component in other scenarios, but I need to stop re-rendering when the Modal opens/close

What I tried is using

shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {

    return this.state.openSimpleModal === nextState.openSimpleModal
}

and deciding if the state of the modal changed and in that case returns false, but it's not working, because of course the modal wont shows.

2
It depends on how you're rendering your component; could you show more of your Modal component? If it's not returning any elements when openSimpleModal is false, for example, there's no way to not re-render since it has to recreate the elements. - Jacob
My understanding is that wehn openSimpleModal is set to false, Father will be dismounted and thus the other component will be dismounted as well? If it is dismounted, they all have to be re-rendered. If your concern is preserving the state, you should store the state in parent component. If your concern is performance, you need to think something else to optimize the rendering. - Anthony Poon

2 Answers

1
votes

In render slave the ChildComponent with the same boolean state?

class Father {

 render() {

  return (
    <div>
    {this.state.openSimpleModal &&  <ChildComponent />}
    <MyModal show={openSimpleModal} />
    </div>
  );
 }
}
1
votes
  1. In your shouldComponentUpdate you are returning true when both are same so it updates. So it should rather be

    shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {
    
        return this.state.openSimpleModal != nextState.openSimpleModal
    }
    
  2. There is no need to care about rerenders if it is not causing any performance issues.
  3. You can use React.memo, React.PureComponent or React.useMemo based on your requirements