Last active
July 28, 2022 13:24
-
-
Save Naedri/d5705fc46971a56e0aba44388b2df138 to your computer and use it in GitHub Desktop.
Comparing `useEffect` runs (React and Ionic flavors).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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