Skip to content

Instantly share code, notes, and snippets.

@Naedri
Last active July 28, 2022 13:24
Show Gist options
  • Save Naedri/d5705fc46971a56e0aba44388b2df138 to your computer and use it in GitHub Desktop.
Save Naedri/d5705fc46971a56e0aba44388b2df138 to your computer and use it in GitHub Desktop.
Comparing `useEffect` runs (React and Ionic flavors).
import { useIonViewWillEnter, IonText } from '@ionic/react';
import { FC, useRef, useEffect } from 'react';
export interface ComponentProps {
data: any;
}
const Component: FC<ComponentProps> = ({ data }: ComponentProps) => {
const compoRef = useRef<HTMLDivElement>(null);
const isFirstRender = useRef(true);
useEffect(() => {
console.log('1) run once: when the FC is initialized');
}, []);
useEffect(() => {
console.log('1-2) run more than once: when the FC is initialized and when data props change');
}, [data]);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
console.log('1) run once: early when the FC is initialized');
} else {
console.log('2) run more than once: lately when data props change');
}
}, [data]);
useIonViewWillEnter(() => {
console.log('0) run never: as we are not in an IonContent, but could have run once before Ionic view entering');
});
return (
<div className="compo" id="compo" ref={compoRef}>
<IonText>{{ JSON.stringify(data) }}</IonText>
</div>
);
};
export default Component;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment