useMountedOnce is a custom React hook that allows you to run a callback function only once when the component is mounted. This hook ensures that the callback is executed only during the component's first render and is not triggered on subsequent re-renders. It’s useful when you need to perform an action (e.g., data fetching, subscriptions) just once after the component has mounted, without triggering it on every render.
Here’s how you can use the useApiService hook in your React component:
useMountedOnce(() => {
const socket = new WebSocket('wss://example.com/socket');
socket.onopen = () => {
console.log('WebSocket connected!');
};
socket.onmessage = (event) => {
console.log('Received message:', event.data);
};
// Cleanup function to close WebSocket connection when the component unmounts
return () => {
socket.close();
console.log('WebSocket connection closed.');
};
});
callback
: The callback function that you want to execute once after the component has mounted.
Feature | useEffect |
useMountedOnce |
---|---|---|
Runs | After every render (unless dependency array is provided) | Only once after the initial render |
Dependencies | Supports dependencies to trigger effect re-run | No need for dependencies (always runs once) |
Cleanup | Supports cleanup for side effects | Optionally supports cleanup inside the callback |
State & Props Updates | Re-runs on state/prop changes (if dependencies change) | Does not re-run on state/prop updates |
Use Case | General side effects (data fetching, DOM manipulation, etc.) | Actions that should only happen once on mount (e.g., initialization, analytics tracking) |