0

link to sandbox

App has state from which a memoized value is computed which is passed to the Options as props. When the state changes due to a callback passed to Option, App is rerendered, causing

  1. a rerender of all of the Options
  2. a rerender of SomeComponent which doesn't even take any props

I am looking for a pattern using React hooks and state management that would allow for only 2 of the Options to be rerendered - the one that is deselected, because its isSelected property goes from true to false, and the one that is selected, because its isSelected property goes from false to true. I do not understand why the other child components, particularly SomeComponent, need to be rerendered, when their props do not change.

user6118986
  • 341
  • 2
  • 15
  • 1
    This is how React works. A re-render of a component will trigger a re-render of all children. What you're attempting to do is an over-optimization, and may actually result in a performance loss rather than the gain you expect. Re-renders are very very fast, and a re-render does not mean any changes are made to the actual DOM. Just trust React to do it's job well until you notice an observable performance problem. – Brian Thompson Mar 30 '22 at 17:22
  • Interesting - so am I correct in saying that the render method being called in code (as determined by console logging in the body of the React functional component) corresponds to a write to the virtual DOM? Then React does its magic to determine whether it needs to update the real DOM? – user6118986 Mar 30 '22 at 17:33
  • Yes. The JSX we write first get's executed to return objects that represent the DOM (`console.log()` to see what I mean). Then React compares the new Virtual DOM with the previous, and determines what places need to actually change. – Brian Thompson Mar 30 '22 at 17:36
  • See [reconciliation](https://reactjs.org/docs/reconciliation.html) for a better and more detailed explanation – Brian Thompson Mar 30 '22 at 17:37

1 Answers1

0

This is typically done with React.memo to make components who's render is only dependant on their props not re-render unless their props change.

See: https://reactjs.org/docs/react-api.html#reactmemo

Chad S.
  • 6,252
  • 15
  • 25