What follows is a simple example:
When you want to update a child without updating the parent, the state must be in the child. You can pass the state getter / setter from the child to the parent to be able to read and update it:
function Child({onMount}) {
const [value, setValue] = useState(0);
useEffect(() => {
onMount([value, setValue]);
}, [onMount, value]);
return (
{value}
);
};
function Parent() {
let value = null;
let setValue = null;
const onChildMount = (dataFromChild) => {
value = dataFromChild[0];
setValue = dataFromChild[1];
};
// Call setValue to update child without updating parent
return (
);
};
Since const [value, setValue] = useState(0);
is in the Child
, only the child component will re render when updating the value. Additionally, since the Parent
receives value
and setValue
at onChildMount
, the parent can use them to update the child without re rendering the parent.