Skip to content

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

Try mounting and unmounting the component and see the status of count update.Check console for mount message

Usage

Import the hook from @abhushanaj/react-hooks and use in required component;

./src/App.tsx
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

  1. When using the useOnMount hook, you don’t need to memoize the callback with React.useCallback or similar. As the callback is not utilized as a dependency in the useEffect, you can pass your callback as is, and rest assured that it will be called only once during mount, regardless of subsequent re-renders.
./src/App.tsx
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

ParameterTypeDescriptionDefault
callback()=>voidThe callback function to run after component mount.N/A