Hook that runs an effect once on mount and cleans up on unmount
Some work should happen once per mounted component: logging a “screen viewed” analytics event, opening a WebSocket, or focusing the first field of a dialog. Implement a React hook, useMountEffect, that runs an effect once after the component mounts and runs its cleanup once when the component unmounts.
function useMountEffect(effect: () => unknown): void
effect exactly once per mount, after the first render has been committed to the DOM (the same timing as useEffect). Never call it during render.effect returns a function, treat it as the cleanup: call it exactly once when the component unmounts, and never on re-renders.effect returns anything that is not a function (for example undefined, or a Promise because it was declared async), ignore the return value. Unmounting must not throw.function CheckoutScreen({ cartId }) {
const [step, setStep] = useState(1);
useMountEffect(() => {
analytics.track('checkout_opened', { cartId });
const socket = openPriceUpdates(cartId);
return () => socket.close();
});
return <button onClick={() => setStep(step + 1)}>Step {step}: continue</button>;
}
// Mount: 'checkout_opened' is tracked once and the socket opens.
// Click 3 times: re-renders only. Nothing is tracked again.
// Leave the screen: socket.close() runs once.
useMountEffect(async () => {
await prefetchShippingRates(); // returns a Promise, which is not a cleanup
});
// Unmounting this component must not throw.
<React.StrictMode> intentionally mounts, unmounts and mounts each component again, so the effect runs twice with the cleanup in between. That is expected. Don’t defeat it with a module-level flag. The tests don’t use StrictMode.Object.assign(window, { useMountEffect }); below “Do not edit below this line”. The tests use it to call your hook.