Rajat Aggarwal
Rajat Aggarwal

Reputation: 454

Does react re-render components that don't depend on state when the state changes?

The StateIndependentComponent is a heavy component and StateDependentComponent is light but the state changes multiple times and quickly.

So, will StateIndependentComponent be re-rendered every time the state changes?

<StateIndependentComponenet />
<StateDependentComponent data={this.state.data} />

Upvotes: 2

Views: 430

Answers (1)

Adam Jeliński
Adam Jeliński

Reputation: 1788

It depends how you implemented your components. By default yes, but you can use React.PureComponent (class components) or React.memo (function components) to make the component only rerender when it's props or state actually change.

class StateIndependentComponenet extends React.PureComponent {
    ...
}

or

const StateIndependentComponenet = React.memo((props) => {
    ...
})

Be sure to care about the note that is in the React docs linked above, because your component will not rerender seemingly randomly if you are mutating state by accident.

Upvotes: 1

Related Questions