0

I have a main component which displays a list of wands through a wand component, and a sibling component which displays the the wands that have been checked.

The problem is when I set the state of wands checked in the Wand when a checkbox is checked, because it sets the state in the parent Wands component, it causes all of the components to re-render.

This is an issue because the checked wand is deselected, because all of the wands are re-rendered.

Ideally I would like to track and pass the list of checked wands when each is clicked from the Wand component, to display all those that have been checked in the WandsChecked component, without causing a mass re-render.

I've been working on this problem on my own for awhile while learning React, and could really use some advice from the community at this point.

Thanks for the advice!

Component Setup:

Wands

--Wand

--WandsChecked


import { useState, useCallback } from 'react';
import WandsChecked from './WandsChecked';

function Wands ({wands}) {
  console.log('Wands re-rendering');
  const [wandsChecked, setWandsChecked]     = useState([]);

return (<>

    <main>
      <div className='grid gap-4 grid-cols-3 grid-rows-3'>
        {wands && wands.map((item => <Wand setWandsChecked={setWandsChecked} someprop={item} />))}
      </div>
      <div className='grid gap-4 grid-cols-3 grid-rows-3'>
          <WandsChecked WandsToCompare={wandsChecked}/>
      </div>
    </main>
</>)


function Wand({setWandsChecked, wand}) {
  console.log('Car re-rendering');

  //FIRED WHEN THE CHECKBOX IS CLICKED
  const asyncfunc = useCallback(async (veh, isChecked) => {
    //SET THE WANDS CHECKED
    //THIS CAUSES ALL THE COMPONENTS TO RERENDER
    setWandsChecked([...wandsChecked, veh]);
  }, []);

  return (<>
    <div className='wand-wrapper basis-1/4'>
      <div className='wand-banner'><input type="checkbox" id={wand.name} value={wand.isChecked} onClick={(e) => asyncfunc(wand, e.target.checked)}/>Check</div>
    </div>

  </>)
}

}

export default Wands;

The way in which I have this setup it is currently causing all components to re-render when I set the state after the checkbox is checked.

QuietCoder
  • 161
  • 1
  • 4
  • https://stackoverflow.com/questions/69317889/best-way-to-use-usememo-react-memo-for-an-array-of-objects-to-prevent-rerender-a useMemo on wands array to prevent re-render on the wands list. (the checked-wands list will need to re-render because the array changes upon check/uncheck) – Eran Dec 09 '22 at 03:51
  • 1
    The wand is probably getting unchecked because it's not controlled. It _appears_ controlled (i.e you're trying to use the `isChecked` value of `wand` until you realise that you're not passing in `wand` to the component but something called `someprop`. It's sounds like you're at an early stage with this and you're looking to do premature optimisation where it's not really necessary. – Andy Dec 09 '22 at 04:13

0 Answers0