Home > Software engineering >  Avoid Rerendering of modal if checkbox is selected
Avoid Rerendering of modal if checkbox is selected

Time:04-27

I have modal like below

const Modal = (second) => {
    console.log("rendering modal..");
    return (
      <Modal isOpen={showModal} onClose={() => setShowModal(false)}>
        <Modal.Content maxWidth="400px" maxHeight="600px">
            <Modal.Body>
            <ScrollViewContent />
          </Modal.Body>
        </Modal.Content>
      </Modal>
    );
  };

And I have checbox inside scrollview like below

const ScrollViewContent = () => {
    return (
      <ScrollView>
        <FormControl mt={4}>
        <Checkbox.Group
          onChange={setGroupValues}
          value={groupValues}
          accessibilityLabel="choose values"
        >
          {projectlist}
        </Checkbox.Group>
      </FormControl>
      </ScrollView>
    );
  };

I am looping the checkbox list using remote json like below

  const projectlist = PjsonList.map((data, key) => {
    return (
      <Checkbox key={data.pname   data.uid} value={data.uid}>
        {data.pname}
      </Checkbox>
    );
  });

My checkbox is appearing and i am able to select , unselect .But evertytime when i check/uncheck i.e when state is updated using setGroupValues , my modal is rendering again creating a blink , how do I avoid the Re-render of the modal , thank you.

CodePudding user response:

You can convert your modal pure component if you want to prevent re-rendering.

import React, {memo} from 'react';

const Modal = (second) => {
    console.log("rendering modal..");
    return (
      <Modal isOpen={showModal} onClose={() => setShowModal(false)}>
        <Modal.Content maxWidth="400px" maxHeight="600px">
            <Modal.Body>
            <ScrollViewContent />
          </Modal.Body>
        </Modal.Content>
      </Modal>
    );
  };

export default memo(Modal);

CodePudding user response:

You can use useMemo() in projectlist. try this:

const projectlist = useMemo(() => PjsonList.map((data, key) => {
    return (
    <Checkbox key={data.pname   data.uid} value={data.uid}>
      {data.pname}
    </Checkbox>
  );
}), []);

and you can use React.memo for modal component with

React.memo(Modal, (nextProps, nextState) => {
  return (
    nextState !== `your states`
  );
})
  • Related