Imagine this method:
export default function useListenDeletedChatMessages(
chatRoomId = undefined,
{
onNext = undefined,
onError = undefined,
} = {}
) {
const { modifyMessage } = useMessages();
const startAt = useRef(new Date());
useEffect(() => {
if (!chatRoomId) return; <-------- !!!!!
// Listen for new deleted messages
const deletedMessagesListener = listenDeletedChatMessages(
chatRoomId,
startAt.current,
modifyMessage,
onNext,
onError
);
// eslint-disable-next-line consistent-return
return () => {
deletedMessagesListener();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatRoomId]);
}
As you can see, I am declaring the parameter "chatRoomId" as optional, because the method will still work without this param (not listening the chat messages).
I have decided to set that param as undefined in this REACT HOOK, because in my UI, at first glance, it is undefined, until an async query is performed after my component mounts.
You may think about doing something like:
if (chatRoomId) {
useListenDeletedChatMessages(chatRoomId);
}
But, in React, hooks cannot be wrapped inside conditionals.
So, my question is:
When should we use optional arguments? Because, for me, something like
function listenChatRoom(roomId = undefined) {}
is like saying to the programmer that he can listen to a room which id is optional (and, in my system, a room always have a unique id), I mean, it has no sense at all.
Any rule of thumb?