useOnMount
Run a callback after a component mounts using the useOnMount hook.
The useOnMount
hook is helpful when you want to run a callback function after the component has mounted. It relies on the React.useEffect()
hook internally.
useOnMount
Mounted: 0 time
Usage
Import the hook from @abhushanaj/react-hooks
and use in required component;
import { useOnMount } from '@abhushanaj/react-hooks';
function App() { useOnMount(() => { console.log('Mounted'); });
return ( <div> <p>I am now mounted!</p> </div> );}
export default App;
Properties
- When using the
useOnMount
hook, you don’t need to memoize the callback withReact.useCallback
or similar. As the callback is not utilized as a dependency in theuseEffect
, you can pass your callback as is, and rest assured that it will be called only once during mount, regardless of subsequent re-renders.
import React from 'react';import { useOnMount } from '@abhushanaj/react-hooks';
function App() { // This is not required at all. const callback = React.useCallback(() => { console.log('Mounted'); }, []);
useOnMount(callback);
return ( <div> <p>I am now mounted!</p> </div> );}
export default App;
API Reference
Parameters
Parameter | Type | Description | Default |
---|---|---|---|
callback | ()=>void | The callback function to run after component mount. | N/A |