JAVASCRIPT
React `useMount` Hook for Effects Running Only on Component Mount
Execute a function only once when a React component mounts, providing a clean way to handle initial setup logic without running on subsequent re-renders.
import { useEffect } from 'react';
const useMount = (callback) => {
useEffect(() => {
callback();
}, []); // Empty dependency array ensures it runs only once on mount
};
export default useMount;
How it works: The `useMount` hook is a simple wrapper around `useEffect` that ensures its callback function is executed only once when the component first mounts. By providing an empty dependency array to `useEffect`, it explicitly tells React not to re-run the effect on subsequent updates, making it ideal for one-time initialization tasks such as fetching data or setting up event listeners that only need to happen once.