Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled component causes unwanted rerender

I have an app that looks like this

class App extends Component {
  state = {
    config: {}
  };
  submitForm(formData) {
    this.setState({
          config: newConfig(formData)
    });
  }

  render() {
    return (
      <div className="App">
        <Form submit={formData => this.submitForm(formData)} />
        <Body config={this.state.config} />
      </div>
    );
  }
}

function Form(props) {
  const QueryBox = styled.div`
    background-color: #1080f2;
    padding: 1em;
  `;

  return (
    <QueryBox>
      <MyForm submit={props.submit} />
    </QueryBox>
  );
}

class MyForm extends React.Component {

  ...

}

Now my problem is that the styled div causes the MyForm component to rerender upon every state change of the App component.

Why is that. Is this the expected behaviour (this would make styled components unusable for me). And is there a way to change it?

like image 584
Jonathan R Avatar asked Oct 18 '25 05:10

Jonathan R


1 Answers

Your QueryBox will be an entirely new component for every render of Form. Move it outside of Form instead and it will work as expected.

const QueryBox = styled.div`
  background-color: #1080f2;
  padding: 1em;
`;

function Form(props) {
  return (
    <QueryBox>
      <MyForm submit={props.submit} />
    </QueryBox>
  );
}
like image 76
Tholle Avatar answered Oct 20 '25 18:10

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!