Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data re rendering with useIonViewDidEnter hook in Ionic React

I'm using useIonViewDidEnter hook to fetch data asynchronously from server. For this example, I created a dummy array to show the re rendering behavior. Can someone explain why the data is populated in the console even after I navigate to other tabs. Will this impact the performance of the app? Can this be made better? Any suggestions are appreciated.

  const [cars, setCars] = useState([] as any);

  const carsList = [{ name: "BMW" }, { name: "Audi" }, { name: "Benz" }];

  useIonViewDidEnter(() => {
    setCars(carsList);
  });

  console.log(cars);

I created a working example using CodeSandbox. Could anyone please help?

like image 683
coderpc Avatar asked May 17 '26 14:05

coderpc


1 Answers

Ionic Framework keeps all of the pages in the DOM and the component is always there to be rendered when you change location.

You can control the rendering by setting a flag to let you know if the component is visible.

const Tab1: React.FC = () => {
  const [cars, setCars] = useState([] as any);
  const [visible, setVisible] = useState(true);

  useIonViewDidEnter(() => {
    console.log("useIonViewWillEnter");
    setCars(carsList);
    setVisible(true);
  });

  useIonViewWillLeave(() => {
    console.log("useIonViewWillLeave");
    setVisible(false);
  });

  if (!visible) return null;

  console.log(cars);

  return ( 
    // RENDER THE REAL TAB CONTENT
  )
}
export default React.memo(Tab1);

See a potential solution: https://codesandbox.io/s/solution-re-rendering-problem-tabs-6qskh

like image 133
Aaron Saunders Avatar answered May 19 '26 04:05

Aaron Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!