react-redux icon indicating copy to clipboard operation
react-redux copied to clipboard

Containers should read directly from state or from ownProps whenever possible?

Open viniciusbo opened this issue 9 years ago • 1 comments

What is the preferred way (or best practice) to populate presentational components from containers: reading directly from state or reading from ownProps whenever possible? Why?

Suppose the following application state:

{ todos: [{ id: 1, text: 'Foo'}] }

Example reading from ownProps:

TodoItem from '../components/TodoItem';
const mapStateToProps = (state, ownProps) => {
  return { data: ownProps.data };
};
const mapDispatchToProps = (dispatch, ownProps) => {
  return { onComplete: () => {} }
};
const TodoItemContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoItem);

class TodoList extends Component {
  // ...
  render() {
    return this.props.items.map(item => {
      return <TodoItemContainer index={item.id} data={item} />;
    });
  }
}

Example reading directly from state:

import TodoItem from '../components/TodoItem';
const mapStateToProps = (state, ownProps) => {
  return { data: state.todos[ownProps.id] };
};
const mapDispatchToProps = (dispatch, ownProps) => {
  return { onComplete: () => {} }
};
const TodoItemContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoItem);

class TodoList extends Component {
  // ...
  render() {
    return this.props.items.map(item => {
      return <TodoItemContainer index={item.id} id={item.id} />;
    });
  }
}

viniciusbo avatar Dec 13 '16 12:12 viniciusbo

You should be reading from state since you don't want to have to pass that state down through multiple layers of components to the container. Also, this will mean only that container will re-render when the state it's looking at changes, rather than your entire application.

timdorr avatar Dec 13 '16 15:12 timdorr