diesel94
diesel94

Reputation: 159

React component in state of component

I have a question about React rerender mechanism. We have a component named Dispatcher, which accept to own props different React components with their props and updates own state to render them. So, it looks like:

class Dispatcher extends React.Component {
 
  state = { ReactClass: null, props: {} }

 
  update = (ReactClass, props) => this.setState({ ReactClass: ReactClass, props: props || {}});

  /*... some code for using update method globally*/
 
  render() {
    let { ReactClass, props } = this.state;

    if (!ReactClass) return null;

    return (<ReactClass {...props}/>);
  }
}

When Dispatcher accepted as ReactClass ComponentA with some props, and then i give to it ComponentB with some props, ComponentA will unmount and ComponentB will mount. But if i give to Dispatcher as prop ComponentA again after ComponentA but with different own props, instead of unmounting/mounting, updating (ComponentDidUpdate) of ComponentA happens. It sounds logical but how React detect (maybe i can read some docs?) that ReactClass actually is the same during rerender of Dispatcher? Why ComponentA updates instead of remounting? Magic. Thanks.

Upvotes: 0

Views: 54

Answers (1)

JeanJacquesGourdin
JeanJacquesGourdin

Reputation: 1843

I think it has to do with the reference to the class ComponentA.

Under the hood react keeps references to every component with keys. That's why when you use

//...
return(
  <>
  {Array(3).fill(0).map(elem => <p>elem<p/>}
  </>
)

React will give you a console error and ask you to give a key prop so that react will be able to keep references and updates accordingly :

//...
return(
  <>
  {Array(3).fill(0).map((elem, index) => <p key={'p'+index}>elem<p/>}
  </>
)

Try to keep ComponentA but change its key when you change the props, I'm pretty sure ComponentA will rerender =)

Upvotes: 1

Related Questions