Lifecycle
Guidelines
Different Mini Program platform provides different lifecycle methods and it made it hard to write
cross-platform codes. For example, the equivalent of React componentDidMount
is attached
in
WeChat while onInit
in Alipay.
So we advise you to use universal hooks in Goji even if Goji mapped all lifecycle methods into their hooks,
Universal hooks
You can use all available hooks from React like useEffect
or useLayoutEffect
.
- Check page or component mounted / unmounted
You can use useEffect
with empty deps []
.
const MyComp = () => {
useEffect(() => {
console.log('component mounted');
return () => {
console.log('component unmounted');
};
}, []);
return null;
};
- Check props changed
You can use useEffect
with props as deps.
const MyComp = ({ id }: { id: string }) => {
const [data, setData] = useState<ResponseData | undefined>(undefined);
useEffect(async () => {
// every time `id` change, fetchAPI will be called
const data = await fetchAPI(id);
setData(data);
}, [id]);
return data ? data : 'loading';
};
For more detail about how to use effect hooks please see Using the Effect Hook.
The callback function in
useEffect
would always run in the next scheduled time slice, usually in therequestAnimationFrame
. If you'd like to run callback immediately after component mounted/updated please useuseLayoutEffect
.
- Get load options
You can use useLoadOptions
:
import { useLoadOptions } from '@goji/core';
const MyComp = () ={
const [loadOptions, setLoadOptions] = useState<LoadOptions | undefined>();
useLoadOptions((options: LoadOptions) ={
setLoadOptions(options);
});
};
We advice to use
useLoadOptions
instead ofunsafe_useOnLoad
because allunsafe_useOnLoad
callback only runs once when the page'sonLoad
run. If a component mounted after the firs time rendering theunsafe_useOnLoad
would never run.
- Check page visibility
You can use useVisibility
to detect whether the page is shown.
import { useVisibility } from '@goji/core';
const MyComp = () ={
useVisibility((shown: boolean) ={
if (shown) {
// onShow codes here
} else {
// onHide codes here
}
});
};
Mapped lifecycle hooks
All lifecycles are mapping to hooks prefixed with unsafe_use
. For example, onLoad
is mapped to
unsafe_useOnLoad
, onPullDownRefresh
is mapped to unsafe_useOnPullDownRefresh
Since Goji use React Context for lifecycle events passing you can use these hooks in any component. So there is no need to use pageLifetimes any more.