Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I prevent parent rerender if child state value changes?

So I want to keep track of all component tree states in one object but the problem is that if I use set state on the child object, the whole component tree seems to rerender and not just child.

Let’s say that I have these components:

const Parent = () => {
  const [ data, setData ] = useState({ parent: 0, child: 0 });

  console.log('parent rerenders but should not', data);
  return (
    <>
      <div>parent value: {data.parent}</div>
      <Child setData={setData} data={data} />
    </>
  );
};


const Child = ({ setData, data }) => {
  console.log('child rerenders and should', data);
  return (
    <>
      <div>child value: {data.child}</div>
      <button onClick={() => setData({ parent: 0, child: 10 })}>
        test
      </button>

    </>
  );
};

So as you can see I change the value in the child but I don’t want parents to rerender unless data.parent changes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question is: is there any way I can have this logic in my app? Remember that I need to somehow keep track of all component tree states in one object. Maybe redux?

>Solution :

You can split the parent comp and child comp using a custom hook.

this is an example of your case.

const Parent = () => {
  // const [ data, setData ] = React.useState({ parent: 0, child: 0 });
  const { data } = useSomeHook();
  console.log('parent rerenders but should not', data);
  return (
    <>
      <div>parent value: {data.parent}</div>
      <Child data={data} />
    </>
  );
};

const useSomeHook = () => {
  const [ data , setData ] = React.useState({ parent: 0, child: 0 });

  return {
    data,
    setData,
  }
}

const Child = ({  data }) => {
  const { setData } =useSomeHook();
  console.log('child rerenders and should', data);
  return (
    <>
      <div>child value: {data.child}</div>
      <button onClick={() => setData({ parent: 0, child: 10 })}>
        test
      </button>
    </>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading