← Back to all snippets
JAVASCRIPT

Execute Code on Component Mount and Unmount with Custom Hooks

Implement `useMount` and `useUnmount` React hooks to run specific logic exactly once when a component is mounted or unmounted, mimicking class component lifecycles.

import { useEffect } from 'react';

const useMount = (callback) => {
  useEffect(() => {
    callback();
  }, []); // Empty dependency array ensures it runs only once on mount
};

const useUnmount = (callback) => {
  useEffect(() => {
    return () => {
      callback();
    };
  }, []); // Empty dependency array ensures cleanup runs only on unmount
};

// Example Usage:
function MyLifecycleComponent() {
  useMount(() => {
    console.log('Component mounted!');
  });

  useUnmount(() => {
    console.log('Component unmounted!');
  });

  return <div>Check console for mount/unmount messages.</div>;
}
How it works: The `useMount` hook executes a provided callback function only once when the component first mounts, similar to `componentDidMount`. The `useUnmount` hook executes a callback only when the component unmounts, acting like `componentWillUnmount`. Both achieve this by leveraging `useEffect` with an empty dependency array, where `useUnmount` specifically uses `useEffect`'s cleanup return function.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs