I am trying to prevent re rendering in a React functional component, but not sure how or what to implement, to achieve that. Reading up suggests using memo, but I don't understand how to implement it here.
The props include 'selectAll' (propType=boolean ), onSelected is a callback function and I use a stateHook for selected.
So, if the 'setSelected(newSelects)' method is called, it goes into an endless reRender loop; I have a work around in the return of the markup, which works, but I would prefer to use and learn and understand managing React's state.
Code:
function OptimiserTableBody(props) {
const {Id, columns, send, onSelected, selectAll} = props;
const [selected, setSelected] = useState([]);
// Retrieve the data
const resOData = useQuery(o_data_query, {
variables: {
id: id,
use: use
},
fetchPolicy: 'cache-and-network'
});
// Create an array from the retrieved data for the table, this is used to create the table rows
let steps = resOData.data != undefined ? resOData.data.jobO.data : [];
useEffect(() => {
if (selectAll === true) {
let newSelects = steps.map((n) => n.workStepId);
setSelected(newSelects);
}
}, [selectAll])
return (
<TableBody>
{steps.map((step, index) => (
let isItemSelected = isSelected(step.workStepId);
// Workaround
if (selectAll === true)
{
isItemSelected = true;
}
return (
<TableRow ... >
<TableCell key={'select'} padding="checkbox" >
<Checkbox
checked={isItemSelected}
inputProps={{ 'aria-labelledby': step.workStepId }}
style={{color: kbaColors.grey1}}
onClick={(event) => handleClick(event, step.workStepId)}
/>
</TableCell>
</TableRow>
))}
</TableBody>
);
}
export default React.memo(OptimiserTableBody);
Thanks