redux functional component selector code example

Example 1: using redux with hooks

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addCount } from "./store/counter/actions";

export const Count = () => {
  const count = useSelector(state => state.counter.count);
  const dispatch = useDispatch();

  return (
    <main>
      <div>Count: {count}</div>
      <button onClick={() => dispatch(addCount())}>Add to count</button>
    </main>
  );
};

Example 2: selector for redux

import { createSelector } from 'reselect';

const getProducts = state => state.products.itemsById;
const getCartItemIds = state => state.currentUser.shoppingCart.itemIds;

export const selectShoppingCartItems = createSelector(
  getProducts,
  getCartItemIds,
  (products, itemIds) => itemIds.map(id => products[id])
);