top of page
Logo der Online Agentur mdwp

PureComponent

React.PureComponent is a base component class in React, introduced in version 15.3.0, that you can use to ensure that your components are not re-rendered unnecessarily. It achieves this by implementing a shallow comparison of props and state in the shouldComponentUpdate lifecycle method.

A shallow comparison means it only checks if the references to the objects have changed and not the actual objects themselves. If the references have not changed, React.PureComponent assumes that the props or state has not changed and therefore does not re-render the component. This can help improve performance for React applications that may have a large number of components that may re-render often.

Here is an example of a React.PureComponent:

```jsx
class MyComponent extends React.PureComponent {
render() {
return (
<div>
{this.props.name}
</div>
)
}
}
```

In this example, the MyComponent will only re-render if the props.name reference changes. If the value is changed to the same string, the component will not re-render since the reference has not changed.

It's important to note that React.PureComponent's shallow props and state comparison only works with simple data structures. Complex data structures, like nested objects and arrays, may produce false negatives because shallow comparison only checks the top layer. For deeper comparison, you may need to implement your own shouldComponentUpdate lifecycle method or use libraries like lodash's _.isEqual for deep comparison.

bottom of page