Using reselect

Use Reselect in Redux connect(mapState) — to avoid frequent re-render.

Bad

  1. let App = ({otherData, resolution}) => (
  2. <div>
  3. <DataContainer data={otherData}/>
  4. <ResolutionContainer resolution={resolution}/>
  5. </div>
  6. );
  7. const doubleRes = (size) => ({
  8. width: size.width * 2,
  9. height: size.height * 2
  10. });
  11. App = connect(state => {
  12. return {
  13. otherData: state.otherData,
  14. resolution: doubleRes(state.resolution)
  15. }
  16. })(App);

In this above case every time otherData in the state changes both DataContainer and ResolutionContainer
will be rendered even when the resolution in the state does not change.
This is because the doubleRes function will always return a new resolution object with a new identity.
If doubleRes is written with Reselect the issue goes away:
Reselect memoizes the last result of the function and returns it when called until new arguments are passed to it.

Good

  1. import { createSelector } from 'reselect';
  2. const doubleRes = createSelector(
  3. r => r.width,
  4. r => r.height,
  5. (width, height) => ({
  6. width: width * 2,
  7. height: height * 2
  8. })
  9. );