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
Advertisement
Answer
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