Home > other >  Can I prevent parent rerender if child state value changes?
Can I prevent parent rerender if child state value changes?

Time:12-27

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.

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?

CodePudding user response:

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>
    </>
  );
};

CodePudding user response:

Parent re renders because you are calling setData and a component re renders when you update one of its state.

Keeping all states in one component IS generally a bad idea. Either give each component their states or use custom hooks to share state logic between components.

  • Related