Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  68] [ 2]  / answers: 1 / hits: 21061  / 6 Years ago, thu, october 25, 2018, 12:00:00

I would like to know if a React component extending React.Component deeply compares an object when trying to decide if it needs to rerender.



For instance, given



const Foo = ({ bar }) => {
return <div>{bar.baz}</div>
}

class App extends React.Component {
constructor() {
super()
this.state = { bar: { baz: 1} }
}

render() {
return <Foo bar={this.state.bar} />
}
}


If inside App, the state bar changes to {baz: 2}, does <Foo /> deeply compare the previous prop bar and the newly received prop?



Incidentally, the docs for PureComponent says




Extend PureComponent ... Or, consider using immutable objects to facilitate fast comparisons of nested data.




But does not go into much more details. Any ideas?


More From » reactjs

 Answers
2

Unless you implement a shouldComponentUpdate lifecycle method yourself, a component extending React.Component won't compare the props before going through a re-render cycle where it compares the previous and current Virtual DOM to decide what to re-render



Also a component extended using React.PureComponent doesn't deeply compare props with prevProps and state with prevState but performs shallow comparison to decide, if at all a re-render is needed or not.



For a Functional component from v16.6.0 onwards, React has introduced a Higher Order Function, React.memo which can be used to make a functional component behave as a React.PureComponent



According to the docs:




React.memo is a higher order component. It’s similar to
React.PureComponent but for function components instead of classes.



It can be used like



const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
});


If your function component renders the same result given the same
props, you can wrap it in a call to React.memo for a performance boost
in some cases by memoizing the result. This means that React will skip
rendering the component, and reuse the last rendered result.



By default it will only shallowly compare complex objects in the props
object. If you want control over the comparison, you can also provide
a custom comparison function as the second argument.



[#53254] Saturday, October 20, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
george

Total Points: 2
Total Questions: 98
Total Answers: 105

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;