Home > OS >  How to not re render the parent of a child component?
How to not re render the parent of a child component?

Time:11-16

I’m having re-rendering issues, any help is greatly appreciated. I tried useMemo and useCallback and it broke the checkbox. I have a component, and inside that component, I display some info in my object. I have let's say an object as such:

fakeObject = {
name: "rectangle"
width: 10
height: 20
visible: true
}

const fakeComponent = () => {
const [checked, setChecked] = React.useState(true);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
    fakeObject["visible"] = event.target.checked;
  };
return(
   <div>
   <h2> {fakeObject.name} </h2>
   <p> The height is {fakeObject.height} </p>
   <Checkbox
      checked={checked}
      onChange={handleChange}
      inputProps={{ 'aria-label': 'controlled' }}
    />
  </div>
)
};

The issue is that every time I click my checkbox it rerenders the whole component. This is a simplified version of my issue but I see that the component uses my fakeObject and that the checkbox changes that but how do I make it so that my whole component doesn't re-render? Thanks for any help

CodePudding user response:

The parent component will be re rendered because you are saving the checked state on the parent component with a useStateHook, if you would like to avoid re render a component you can use memo but you need to remove the hook where you want to avoid re render.

CodePudding user response:

How to not re render the parent of a child component?

It's possible, but you would have to move all the logic responsible for checking the checkbox to the child component (Child).

const Checkbox = () => {
  const [checked, setChecked] = useState(false);
  console.log('child re-render');

  return (
    <input
      value={checked}
      type="checkbox"
      onChange={() => setChecked((prev) => !prev)}
    />
  );
};

Then, you don't even need to worry about memo.

Codesandbox: https://codesandbox.io/s/modest-star-y0z3xt?file=/src/App.js

  • Related