Accepts two functions to be performed during the component's lifecycle.
The first one will be fired after component did mount, the second right before the component unmounts.
- Encloses the "lifecycle hooks" such as
useDidMount
anduseWillUnmount
; - It's as a shortcut to
useEffect(onMount, [])
anduseEffect(() => () => willUnmount, [])
;
import { useCallback } from 'react';
import { useLifecycle } from 'beautiful-react-hooks';
/**
* useDidMount example component
*/
const LifeCycleComponent = () => {
const onMount = useCallback(() => {
console.log('Component did mount');
}, []);
const onUnmount = useCallback(() => {
console.log('Component will unmount');
}, []);
useLifecycle(onMount, onUnmount);
return (
<DisplayDemo>
Check the javascript console
</DisplayDemo>
);
};
<LifeCycleComponent />
if no parameters are provided, the returned object of handler setters can be used to
set the useDidMount
and useWillUnmount
handlers, as long as they are immediately invoked.
Please note: the returned handler setters are meant to change the value of the callback reference only, they do not cause the component rerender nor should not be invoked asynchronously.
import { useLifecycle } from 'beautiful-react-hooks';
const ComponentDidMount = () => {
const { onDidMount, onWillUnmount } = useLifecycle();
onDidMount(() => {
console.log('Component did mount');
});
onWillUnmount(() => {
console.log('Component will unmount');
});
return (
<DisplayDemo>
Check the javascript console
</DisplayDemo>
);
};
<ComponentDidMount />
When using a React function component you should not really think of it in terms of "lifecycle".
The useLifecycle
hook is indeed intended as a shortcut to useEffect(onMount, [])
and
useEffect(() => () => willUnmount, [])
.
To deep understanding useEffect
, what it is and how it should be properly used, please read
"A complete guide to useEffect"
by Dan Abramov
- When in need of performing a function after the component did mount
- When in need of performing a function right before the component unmounts
- When in need of a shortcut to the component lifecycle
- You can't use it asynchronously since this will break the rules of hooks
- If using the handler setters, they should not be used asynchronously but immediately invoked.