更新时间:2023-12-02 19:54:34
You should use memoization (useCallback
/React.memo
) and rewrite handle logic with functional updates.
Also, you avoid Child
to render, since you have a new value
after rendering.
// Make a stable callback
const onChangeHandle = useCallback((event, id) => {
setSelectedChild((updatedArray) => {
if (event.target.checked) {
if (!updatedArray.includes(id)) {
return [...updatedArray, id];
}
} else {
return updatedArray.filter((currId) => currId !== id);
}
return updatedArray;
});
}, []);
// Memoize the component
const MemoChild = React.memo(Child);
const MemoSubChild = React.memo(SubChild);