0

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?

Raul
  • 2,673
  • 1
  • 15
  • 52

1 Answers1

0

If you have multiple components and hooks that depend on this room id, perhaps it's better not to mount them to begin with until you have an id. Then they can assume that the id is always defined and won't have to perform all these weird checks.

Summer
  • 1,175
  • 8
  • 18