Blog>
Snippets

Connecting Redux State to React Components

Provide an example of a React container component connected to the Redux store, illustrating the use of mapStateToProps and mapDispatchToProps to bind state and dispatch functions to the component's props.
import { connect } from 'react-redux';
import { incrementCounter, decrementCounter } from './actionCreators';

// React component that displays a counter
function Counter({ count, onIncrement, onDecrement }) {
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={onIncrement}>Increment</button>
      <button onClick={onDecrement}>Decrement</button>
    </div>
  );
}

// Maps state from the redux store to props
function mapStateToProps(state) {
  return {
    count: state.count
  };
}

// Maps dispatch actions to props
function mapDispatchToProps(dispatch) {
  return {
    onIncrement: () => dispatch(incrementCounter()),
    onDecrement: () => dispatch(decrementCounter())
  };
}

// Connects the React component to the Redux store
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
This example illustrates a React component named Counter with two props: count, onIncrement, and onDecrement. mapStateToProps is used to map the count state from the Redux store to the component's count prop. mapDispatchToProps is used to map dispatch actions incrementCounter and decrementCounter to the component's onIncrement and onDecrement props, respectively. Finally, the Counter component is connected to the Redux store using the connect() function from react-redux.