How to keep components clean when defining functions in smart containers?

In my application, I use response, redux and immutablejs. The store is unchanged and matched with the requisite. When matching the sending to the details, I provide auxiliary functions. Helper functions are comparable to this piece of code in the redux TodoList example:

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

The problem now is that my pure components display too often: the connection above creates a function onTodoClickfor each connection. When PureRenderMixin does not deeply compile currentProps for newProps, it marks the component as mustUpdate because the pointers have changed.

How to define helper functions in containers while keeping components low below?

I already looked at reselection, but planned to use it only to calculate the derived state in mapStateToProps. Is it better to just create a selector for each connection, so that your functions are also remembered?

+4
source share
1 answer

It might be a hack, but you can simply memoize this function based on a parameter dispatch(assuming redux always sends the same function to the same repository):

let lastDispatch;
let dispatchProps;
const mapDispatchToProps = (dispatch) => {
  if (!dispatchProps || dispatch !== lastDispatch) {
    dispatchProps = {
      onTodoClick: (id) => {
        dispatch(toggleTodo(id))
      }
    }
    lastDispatch = dispatch;
  }
  return dispatchProps;
}

or using lodash memoize:

const mapDispatchToProps = _.memoize((dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
})

UPDATE: this is not a hack, it looks like their official docs:

. , , mapDispatchToProps() . mapDispatchToProps() . memoization . № 279 , . .

: https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options

+2

Source: https://habr.com/ru/post/1653016/


All Articles