Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

javascript - React rerendering list

I have a react page that has several components on it with a state that shows a modal. I dont want all the components in the app to re render when the modal shows.

const CustomersPage = () => {
  const [showModal, setShowModal] = useState(false);
  const dataSource = [...omitted data]

  return (
    <>
      <Modal
        visible={showModal} />

      <div>
        <div>
          <div>
            <Button type="primary" onClick={() => setShowModal(true)}>
              Create 
            </Button>
          </div>

          <CustomForm />
        </div>

        <CustomList dataSource={dataSource} />
      </div>
    </>
  );
};

When the showModal value changes, the components CustomForm component and the CustomList component re renders but I dont want them to re render every time the modal shows because the list can have over 100 components. How can I do this?

Edit.

const CustomList = ({ dataSource }) => {
  return (
    <div>
      {dataSource?.map(i => (
        <CustomCard
          id={i.id}
          ...other props
        />
      ))}
    </div>
  );
};

const CustomCard = ({
  ... props
}) => {

  return (
    <>
      <Card
       ...omitted properties
      </Card>
    </>
  );
};
question from:https://stackoverflow.com/questions/65603049/react-rerendering-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can wrap the List and Form components in a React.memo component.

This way they will only re-render when their props change their identity.

See:

https://scotch.io/tutorials/react-166-reactmemo-for-functional-components-rendering-control


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...