react-redux
react-redux copied to clipboard
Containers should read directly from state or from ownProps whenever possible?
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} />;
});
}
}
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.