import React, { memo, PureComponent } from "react";
import { useSelector, useDispatch } from "react-redux";
import { createSelector } from "reselect";
import { add1, add2, add3 } from "../../store/actions/counter";
const Items = memo(({ items }) => {
console.log("items rerender");
return (
<ul>
{items.map((item) => (
<Item item={item} key={item} />
))}
</ul>
);
});
class Italic extends PureComponent {
render() {
return <i>Item</i>;
}
}
class Item extends PureComponent {
render() {
const Tag = this.props.item % 2 ? Italic : "li";
return <Tag>Item</Tag>;
}
}
const itemsSelector = createSelector(
(state) => state.counter.counter1,
(state) => state.counter.counter2,
(counter1, counter2) => Array.from(Array(counter1 * counter2).keys())
);
const Reselect = () => {
const dispatch = useDispatch();
const items = useSelector(itemsSelector);
const { counter1, counter2, counter3 } = useSelector(
(state) => state.counter
);
// const items = useMemo(
// () => Array.from(Array(counter1 * counter2).keys()),
// [counter2, counter1]
// );
const handleAddCounter = () => {
dispatch(add1());
};
const handleAddCounter2 = () => {
dispatch(add2());
};
const handleAddCounter3 = () => {
dispatch(add3());
};
return (
<div>
<button onClick={handleAddCounter}>Add ({counter1})</button>
<button onClick={handleAddCounter2}>Add2 ({counter2})</button>
<button onClick={handleAddCounter3}>Add3 ({counter3})</button>
<Items items={items} />
</div>
);
};
export default Reselect;
const items = useSelector(itemsSelector);
const items = useMemo(
() => Array.from(Array(counter1 * counter2).keys()),
[counter2, counter1]
);