Modal inside FlastList React Native

29 views Asked by At

I am creating a Modal inside a flatlist, but when i close the modal, the whole flatlist re-renders. I know this is because the useState of modal. How can I solve this??

I dont know what to do to prevent the whole modal from re-rendering

1

There are 1 answers

0
Hamude Shahin On BEST ANSWER

You can try using React.memo with Context API/redux to prevent the re-render.

for example: using memo

const FlatlistComponent = React.memo(({ data }) => {
  // Your flatlist code here
});

actually, you can combine the 2 solutions together to get better performance. Like This;

import React, { useState } from 'react';

const FlatlistComponent = ({ data }) => {
  const [openModals, setOpenModals] = useState({});

  const handleOpenModal = (itemId) => {
    setOpenModals({ ...openModals, [itemId]: true }); // redux action
  };

  const handleCloseModal = (itemId) => {
    setOpenModals({ ...openModals, [itemId]: false }); // redux action
  };

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>
          {item.title}
          <button onClick={() => handleOpenModal(item.id)}>Open Modal</button>
          {openModals[item.id] && (
            <div>
              Modal content
              <button onClick={() => handleCloseModal(item.id)}>Close Modal</button>
            </div>
          )}
        </li>
      ))}
    </ul>
  );
};

export default React.memo(FlatlistComponent); // using React.memo here

I hope this will help you.