React.memo
uses a shallow comparison to determine if the props are equal, but I need to pass an object or array as prop, so I went into an areEqual
condition, but the currentProps
and nextProps
values are always the same. I mean, the component does not render.
Lets say this:
export default function App() {
const [data, setData] = useState([
{
name: "First name",
amount: 0
},
{
name: "Other name",
amount: 0
}
]);
const [value, setValue] = useState("");
return (
<>
<input
type="text"
placeholder="Type in for test"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
<br />
<input
type="button"
value="Click to increment first!"
onClick={() => {
const temp = [...data];
temp[0].amount += 1;
setData(temp);
}}
/>
<input
type="button"
value="Click to increment other!"
onClick={() => {
const temp = [...data];
temp[1].amount += 1;
setData(temp);
}}
/>
<br />
<Child data={data} />
</>
);
}
and
const Child = ({ data }) => {
const count = useRef(0);
return (
<>
{data &&
data.map((obj, index) => {
return obj.name + "-" + obj.amount;
})}
<br />
Count: {count.current++}
</>
);
};
const areEqual = (currentProps, nextProps) => {
console.log(currentProps.data[0].amount, nextProps.data[0].amount);
console.log(currentProps.data[1].amount, nextProps.data[1].amount);
if (
currentProps.data[0].amount === nextProps.data[0].amount &&
currentProps.data[1].amount === nextProps.data[1].amount
) {
return true;
}
return false;
};
export default memo(Child, areEqual);
but no matter what always currentProps and nextProps are returning the very same value:
Everything is on this sandbox. What am I missing here?